Locate any decimal value inside a matrix?

13 visualizzazioni (ultimi 30 giorni)
Jose Grimaldo
Jose Grimaldo il 20 Ott 2019
Commentato: dpb il 20 Ott 2019
Im trying to find any values that are not whole numbers inside a 3x3 matrix
x=[1 2.5 4;5 3 3.2;4 9 2]
I want to use the for loop to check every value inside the matrix.
This is my code so far.
w=mod(x,1)~=0; %checking for whole numbers in the matrix
d=x(w) %this are the values that failed the whole number test
[r,c]=find(w); %location of those values
How would i used the for loop?
  1 Commento
dpb
dpb il 20 Ott 2019
Why would you want to use a for loop here? The solution you've shown uses the array addressing features of MATLAB precisely how they're supposed to be used. There's nothing inherently wrong with for, but save it for where it's needed.
Is it homework assignment that has that as a requirement by any chance?
A slightly more shorthand way would be
[r,c]=find(fix(x)~=x);
that is a little more efficient than mod() altho with small array sizes it won't make any difference of note.

Accedi per commentare.

Risposte (1)

Stephan
Stephan il 20 Ott 2019
Modificato: Stephan il 20 Ott 2019
Why use an ineffficient loop instead of vectorized inbuilt functions? Try:
x=[1 2.5 4;5 3 3.2;4 9 2]
idx = find(mod(x,1)~=0)
values = x(idx)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by