필터 지우기
필터 지우기

am trying to get the non zero minimum values from all the rows. Am getting the correct minimum values but the indices for minimum values for the first and second rows are wrong. Suggest me where I am wrong

조회 수: 10 (최근 30일)
C=[0,10,8,9,7;10,0,10,5,6;8,10,0,8,9;9,5,8,0,6;7,6,9,6,0]; j=5; for n=1:j e=C(n,:); [M(n),I(n)]=min(e(e>0)); end disp(M); disp(I);

채택된 답변

KSSV
KSSV 2018년 4월 23일
matC=[0,10,8,9,7;10,0,10,5,6;8,10,0,8,9;9,5,8,0,6;7,6,9,6,0];
matC(matC==0) = NaN ;
j=5;
for n=1:j
e=matC(n,:);
[M(n),I(n)]=min(e);
end
disp(M);
disp(I);
  댓글 수: 2
akash sonnad
akash sonnad 2018년 4월 23일
It's working, Thank you. Can you please elaborate on the code matC (matC == 0) = NaN;
KSSV
KSSV 2018년 4월 23일

You are picking up minimum value greater then 0.....so that line replaces all zeros in the matrix with NaN. e(e>0) picks only non-zero values..and gives minimum, this will give different index when compared to original matrix.

Note: You need not to use loops for this...you can striagh away use min on matrix.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2018년 4월 23일
편집: Stephen23 2018년 4월 23일
There is no point in wasting your time writing ugly for loops, because the MATLAB function min does exactly what you want already, much more efficiently than anything you could write using a loop:
>> C = [0,10,8,9,7;10,0,10,5,6;8,10,0,8,9;9,5,8,0,6;7,6,9,6,0];
>> C(C==0) = NaN; % convert zeros to NaN
>> [val,idx] = min(C,[],1)
val =
7 5 8 5 6
idx =
5 4 1 2 2
And that is all. MATLAB is a neat high-level language, so it should not be written as if it was an ugly low-level language like C++.

카테고리

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