Search code examples
matlabmatrixindexingextractregion

Search for max value in a specified region of a matrix then extract a section of the matrix around the max value


I'm trying to extract a specific region of a matrix and then find the max value within that region and extract the values around it to form a new 9x9 matrix.

This is what I've found so far that I think will need to be implemented:

% extract region
BRegion = B(rowStart:rowEnd, colStart:colEnd);
% find max value and get its index
[value, k] = max(BRegion(:));
[i, j] = ind2sub(size(BRegion), k);
% move indexes to correct spot in matrix 
i = i + rowStart-1;
j = j + colStart-1; 

after the max value has been found in the region with it's index, how do i build the new matrix from taking the values in a 9x9 area around it and using the max value as the center?


Solution

  • % extract region
    rowstart = 300;
    rowend = 500;
    colstart = 3500;
    colend = 4500;
    BRegion = B(rowstart:rowend, colstart:colend);
    
    % find max value and get its index
    [value, k] = max(BRegion(:)); 
    [i, j] = ind2sub(size(BRegion), k);
    
    % move indexes to correct spot in matrix
    i = i + rowstart-1;
    j = j + colstart-1;
    
    % creates new matrix
    new_row_begin = i-4;
    new_row_end = i+4;
    new_col_begin = j-4;
    new_col_end = j+4;
    
    newmat = B(new_row_begin:new_row_end,new_col_begin:new_col_end);