Locate any decimal value inside a matrix?

12 Ansichten (letzte 30 Tage)
Jose Grimaldo
Jose Grimaldo am 20 Okt. 2019
Kommentiert: dpb am 20 Okt. 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 Kommentar
dpb
dpb am 20 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephan
Stephan am 20 Okt. 2019
Bearbeitet: Stephan am 20 Okt. 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)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by