Minimum in a matrix! and its location
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
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.
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!