Locate any decimal value inside a matrix?

11 views (last 30 days)
Jose Grimaldo
Jose Grimaldo on 20 Oct 2019
Commented: dpb on 20 Oct 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 Comment
dpb
dpb on 20 Oct 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.

Sign in to comment.

Answers (1)

Stephan
Stephan on 20 Oct 2019
Edited: Stephan on 20 Oct 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)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!