Locate any decimal value inside a matrix?

조회 수: 11 (최근 30일)
Jose Grimaldo
Jose Grimaldo 2019년 10월 20일
댓글: dpb 2019년 10월 20일
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