Minimum in a matrix! and its location

5 views (last 30 days)
Changoleon on 15 Nov 2016
Commented: Changoleon on 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!
Sina

Alexandra Harkai on 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
Changoleon on 15 Nov 2016
This is GREAT! Thank you

Jan on 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.