File Exchange

image thumbnail

how to read surrounding matrix elements following list of coordinates

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

1 Download

Updated 04 Apr 2016

View License

answer to matlab question
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 (, 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(...

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!