File Exchange

image thumbnail

how to read surrounding matrix elements following list of coordinates

version 1.0.0.0 (657 Bytes) by John BG
how to read surrounding matrix elements following list of coordinates answer to reddit.com question

1 Download

Updated 04 Apr 2016

View License

answer to reddit.com matlab question
https://www.reddit.com/r/matlab/comments/4d1r6y/is_it_possible_to_convert_mutliple_local_regions
Q:
For example, if I have a 10×10 matrix, and I have a list of n coordinates in that matrix, I would like to take a 3×3 region surrounding each coordinate, resize it to be a length 9 vector, and then stack all the vectors into a 9×n matrix. I know I could write a for loop to do this but that seems gross, though probably what I'll end up doing.

Cite As

John BG (2021). how to read surrounding matrix elements following list of coordinates (https://www.mathworks.com/matlabcentral/fileexchange/56345-how-to-read-surrounding-matrix-elements-following-list-of-coordinates), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

Stephen Cobeldick

A script has been provided (not a function) and a reference given to some discussion thread, so presumably the author intends this as a model solution to the task discussed on that thread. It is however an overly-complicated solution: it creates six intermediate variables, uses the totally superfluous SUB2IND, and also relies on the third party function COMBINATIONS. Not only that, the author does not preallocate the output cell array, so the task is going to be slower than it needs to be (proportional to the number of requested submatrices: ouch!). Why so complicated? The code also loses the shape of the submatrices, giving vector outputs (so a 2x3 and a 3x2 submatrix cannot be distinguished).

For a much simpler, faster, and neater solution (using a similar concept, but keeping the submatrix shape intact):

out = cell(size(coords,1),1);
for k = 1:size(coords,1)
out{k} = testMatrix(...
max(1,coords(k,1)-1):min(end,coords(k,1)+1),...
max(1,coords(k,2)-1):min(end,coords(k,2)+1));
end

It uses no third party functions, creates no intermediate variables, does not use SUB2IND, uses half the number of lines of code, uses only basic MATLAB indexing, and is more than ten times faster to run (1000 iterations using the author's test examples):

Elapsed time is 13.0247 seconds. % this submission
Elapsed time is 1.14107 seconds. % my simpler solution

Although this submission does work (two stars) the fact that it is clearly half-baked and overly complicated makes it of questionable value to others... and the |clc| and |clear| at the start of the script just deleted all of my work!

PS: The referenced thread's MATLAB advice: caecus caeco dux.

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!