Iterate over specified dimensions in a matrix to find minimum value

2 views (last 30 days)
I have a 180x180 matrix of random integers. What I want is to scan the rows and columns and find the cell with the minimum value. However, I do not want to scan the entire matrix, just rows and columns up to a specified value. I set up the matrix properly and dx and dy are the restraints on where to look in the matrix. However, I am getting multiple minimum values in my for loop. Any ideas how to change this to get the one minimum value?
%This sets up a 180x180 matrix with 16 total zones that each have
%specified range of random integers generated (random numbers represent
%population count in that specified area). Each element represents a
%1km x 1km area of land.
clear all
clc
N1 = randi([1,500],45,45);
N2 = randi([25,1000],45,45);
N3 = randi([100,2200],45,45);
N4 = randi([5,700],45,45);
N5 = randi([100,500],45,45);
N6 = randi([800,3500],45,45);
N7 = randi([1000,10000],45,45);
N8 = randi([15,1000],45,45);
N9 = randi([250,900],45,45);
N10 = randi([5000,11000],45,45);
N11 = randi([1750,9000],45,45);
N12 = randi([25,890],45,45);
N13 = randi([2000,7500],45,45);
N14 = randi([200,2300],45,45);
N15 = randi([25,750],45,45);
N16 = randi([50,1323],45,45);
N = [N1 N2 N3 N4;
N5 N6 N7 N8;
N9 N10 N11 N12;
N13 N14 N15 N16];
[rows, columns] = size(N); % [x,y]
dx = 3;
dy = 10;
for i = 1:rows
for j = 1:columns
if i <= dx
if j <= dy
M = min(N(i,j))
end
end
end
end

Accepted Answer

Guillaume
Guillaume on 28 Mar 2017
Edited: Guillaume on 28 Mar 2017
There's absolutely no reason to use a loop. Use basic indexing to get the portion of matrix that interest you:
N(1:dx, 1:dy)
You can then apply whatever function you want on this. If you want to find the value of the minimum of that submatrix:
M = min(min(N(1:dx, 1:dy)));
If you want the location of that minimum:
[row, column] = find(M == N(1:dx, 1:dy));
Note that your dx, dy names are misleading. x is usually understood as the horizontal coordinate, that is the columns and y is usually understood as rows. You'd be better off naming your variables dr, dc.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!