Locate any decimal value inside a matrix?

12 次查看(过去 30 天)
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 个评论
dpb
dpb 2019-10-20
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.

请先登录,再进行评论。

回答(1 个)

Stephan
Stephan 2019-10-20
编辑:Stephan 2019-10-20
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)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by