Minimum in a matrix! and its location

2 Ansichten (letzte 30 Tage)
Changoleon
Changoleon am 15 Nov. 2016
Kommentiert: Changoleon am 15 Nov. 2016
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

Akzeptierte Antwort

Alexandra Harkai
Alexandra Harkai am 15 Nov. 2016
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 Kommentare
John D'Errico
John D'Errico am 15 Nov. 2016
+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 am 15 Nov. 2016
This is GREAT! Thank you

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 15 Nov. 2016
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.

Kategorien

Mehr zu Debugging and Analysis finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by