MATLAB Answers


Vectorization, check if points coordinate is exist in an image or no

Asked by Mahsa
on 9 Oct 2017
Latest activity Commented on by Mahsa
on 12 Oct 2017
Can anyone help me to vectorize this for loop. It is basically ckecking if the x and y coordinate of is one in N matrix or not. Thank you
for i = 1:length(coordinates)
DD = coordinates(i,:);
DDD = N(DD(1),DD(2));
if DDD ==1
%%%if the dicom point is inside the mask
signVector(i) = -1;
%%%if the dicom point is outside the mask
signVector(i) = +1;


Sign in to comment.

3 Answers

Answer by Teja Muppirala
on 10 Oct 2017
 Accepted Answer

signVector = ones(size(coordinates,1),1);
inds = sub2ind(size(N),coordinates(:,1),coordinates(:,2)); % Convert to linear indices
signVector( N(inds)==1 ) = -1;

  1 Comment

Thank you. I was not aware of sub2ind function.

Sign in to comment.

Answer by Andrei Bobrov
on 9 Oct 2017
Edited by Andrei Bobrov
on 9 Oct 2017

ii = coordinates;
d3 = N(ii(:,1),ii(:,2));
signVector = -ones(numel(d3),1);
signVector(d3 ~= 1) = 1;


Thank you. but it did not work d3 should be a vector not a matrix
Give us code, or a .mat file, to generate coordinates so we can see what you're seeing.

Sign in to comment.

Answer by Image Analyst
on 9 Oct 2017

Be careful. If coordinates is an array of (x,y) and N is an array, then you'll need to check N(y, x), not N(x,y) as you have perhaps done. Remember (row, column) is (y, x) NOT (x,y).

  1 Comment

Sign in to comment.