Minimum in a matrix! and its location

조회 수: 2 (최근 30일)
Changoleon
Changoleon 2016년 11월 15일
댓글: Changoleon 2016년 11월 15일
Hi. I have a 4 by 4 matrix and I want to find the minimum of each row and also want to find where that minimum is located in each row. Folowing is what I have done.
a = [ 1 2 3 0; 7 5 4 6; 9 8 10 11; 12 13 14 15];
for h=1:4 % 4 is the size of matrice a!
mina = min(a(h,:));
ok = find(a(h,:)== mina);
CG(:,h) = [h,ok];
end
When I run this I get the out put CG Which finds me the minimum value in each row along with its location in corresponding row.
Now I want to do the same to a much bigger matrix. Now the size of matrix "a" is 75*75. But when I run the code above, I get the error which says : "Subscripted assignment dimension mismatch." I believe the reason for that is there are two minimums in some of the rows. For example the minimum value in row one is 0. But there are two zeros in row one so MATLAB is having hard time finding which location to give as out put. However it is not important for me which location of zero it gives to me. So the question is how do I manipulate my code or my matrix to get the output that I want ( the minimum value and its location)? The code must somehow work for all rows and it also should work if there are more than two equal minimum values in any row!
Thanks in advance
Sina

채택된 답변

Alexandra Harkai
Alexandra Harkai 2016년 11월 15일
There is no need to loop through the rows, you can specify the 'by-dimension' minimum like this:
a = [ 1 2 3 0; 7 5 4 6; 9 8 10 11; 12 13 14 15];
[mina, idx] = min(a, [], 2);
CG = [mina, idx]; % minimum value in each row along with its location in corresponding row
  댓글 수: 2
John D'Errico
John D'Errico 2016년 11월 15일
+1. This goes to show that reading the help for a tool like min (or max) will often solve your problems. Too often, the tool developers have foreseen such needs, and solved them for you.
Changoleon
Changoleon 2016년 11월 15일
This is GREAT! Thank you

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

추가 답변 (1개)

Jan
Jan 2016년 11월 15일
The problem is not the size of input, but if teh value of the minimum occurres more than once. Simply use the debugger to identify the problem:
dbstop if error
Then run your code again until it stops at the error. Then check the values in the command window:
size(CG(:,h))
h, ok
Now decide what you want to achieve in case of multiple minimum values. Perhaps:
a = [ 1 2 3 0; 7 5 4 6; 9 8 10 11; 12 13 14 15];
GC_C = cell(1, size(a, 1));
for h = 1:size(a, 1)
mina = min(a(h,:));
ok = find(a(h,:)== mina);
CG_C{h} = [h, ok];
end
Note that the elements of CG_C can have different sizes now.

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by