Minimum cell of a matrix
Show older comments
I am trying to find the minimum-value cell of a matrix. To simplify, I take a 3X3 matrix, I tried this but no luck.
Row1=2;
Col1=2;%This is the mid-cell of the 3X3 Matrix
min=99;
if B(Row1,Col1)~=0
for Row =-1:1:1
for Col==-1:1:1 % this gets the adjacent cells of the 3X3 matrix
if B(Row+Row1, Col+Col1)<min
min=B(Row+Row1,Col+Col1);
Answers (1)
Marc Jakobi
on 11 Oct 2016
Edited: Marc Jakobi
on 11 Oct 2016
You need to end every loop and if statement with an end keyword
Min=inf;
for Row =1:size(B,1)
for Col==1:size(B,2)
if B(Row, Col)<Min
Min=B(Row,Col);
end
end
end
Is this a homework assignment? If not, you can also just use
m = Min(B(:));
10 Comments
Ken
on 11 Oct 2016
Marc Jakobi
on 12 Oct 2016
You are making it a lot more complicated than you need to. The code I posted works on any size.
Marc Jakobi
on 12 Oct 2016
To get the coordinates:
Min=inf;
for Row =1:size(B,1)
for Col==1:size(B,2)
if B(Row, Col)<Min
rI = Row; %row index
cI = Col; %column index
Min=B(Row,Col);
end
end
end
coordinates = [rI, cI];
or:
Min = min(B(:));
[rI, cI] = find(B == Min, 1);
coordinates = [rI, cI];
Ken
on 12 Oct 2016
Edited: Walter Roberson
on 12 Oct 2016
Walter Roberson
on 12 Oct 2016
Use blockproc() with a window of 1 and a margin of [1 1] so that a 3 x 3 matrix will be received by the calculation function. Watch out for the behavior at the edges though; blockproc() offers several different approaches for the edges.
Ken
on 12 Oct 2016
Walter Roberson
on 13 Oct 2016
blockproc(YourMatrix, [1 1], @(block) min(block.data(:)), 'BorderSize', [1 1])
Ken
on 15 Oct 2016
Walter Roberson
on 16 Oct 2016
Yes, block.data would be the 3 x 3 matrix currently being examined.
Categories
Find more on Linear and Nonlinear Regression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!