Select pixels from a matrix given the centers ?

1 view (last 30 days)
Suppose we have a given matrix (I) and a structure containing some centers of the matrix before.
For example:
In this case, I is a 9x9 matrix and we have the centers: a22, a63, a45, a26. Normally the number of centers is a square number.
Suppose we want to select all the pixels far from the centers of +1 position on the rows and +3 positions on the columns
The new matrix (A) will be:
My code is:
for c = 1:n
for r = 1:n
uno=Struttu.x(c + ( (r-1) * n));
due=Struttu.y(c + ( (r-1) * n));
A(r,c) = (I( uno +3 , due +1));
end
end
where n*n is the total number of centers.
This code works fine, but is there a faster way to implement it?

Accepted Answer

DGM
DGM on 28 Mar 2023
Edited: DGM on 28 Mar 2023
For addressing scattered points, use sub2ind(). Here's an example.
% this is your array
M = reshape(0:99,10,10)
M = 10×10
0 10 20 30 40 50 60 70 80 90 1 11 21 31 41 51 61 71 81 91 2 12 22 32 42 52 62 72 82 92 3 13 23 33 43 53 63 73 83 93 4 14 24 34 44 54 64 74 84 94 5 15 25 35 45 55 65 75 85 95 6 16 26 36 46 56 66 76 86 96 7 17 27 37 47 57 67 77 87 97 8 18 28 38 48 58 68 78 88 98 9 19 29 39 49 59 69 79 89 99
% these are the "centers" [row col]
% note that indexing is not zero-based in MATLAB
A = [2 2;
6 3;
4 5;
2 6]+1;
% get sizes
sz = size(M);
% these are the array values at those positions
Acenter = M(sub2ind(sz,A(:,1),A(:,2)))
Acenter = 4×1
22 36 54 62
% these are the array values at a given offset
% you'll have to decide how to handle cases where offset position
% is outside the array boundaries. I'm just clamping them.
offset = [3 1]; % [row col]
samplerows = min(max(A(:,1) + offset(1),1),sz(1));
samplecols = min(max(A(:,2) + offset(2),1),sz(2));
Aoffset = M(sub2ind(sz,samplerows,samplecols))
Aoffset = 4×1
35 49 67 75

More Answers (1)

Image Analyst
Image Analyst on 26 Mar 2023
Yes, you can use meshgrid. Code is in the FAQ: https://matlab.fandom.com/wiki/FAQ#How_do_I_create_a_circle?
Your x and y have to be column and row indexes of course.
Let me know if you can't figure it out.
  4 Comments
MementoMori
MementoMori on 28 Mar 2023
No, I want only the pixel that is in the position (+3,+1) with respect to the center
Image Analyst
Image Analyst on 28 Mar 2023
Edited: Image Analyst on 28 Mar 2023
centerRow = ceil(size(m, 1)/2);
centerCol = ceil(size(m, 2)/2);
youWant = m(centerRow + 3, centerCol + 1)
To learn other fundamental concepts, invest 2 hours of your time here:

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!