How can I change the values of multiple points in a matrix?
I have a matrix that is [500x500]. I have another matrix that is [2x100] that contains coordinate pairs that could be inside the first 开发者_如何学运维matrix. I would like to be able to change all the values of the first matrix to zero, without a loop.
mtx = magic(500);
co_ords = [30,50,70; 30,50,70];
mtx(co_ords) = 0;
You can do this using the function SUB2IND to convert your pairs of subscripts into a linear index:
mtx(sub2ind(size(mtx),co_ords(1,:),co_ords(2,:))) = 0;
Another answer:
mtx(co_ords(1,:)+(co_ords(2,:)-1)*500)=0;
I've stumbled upon this question while I was looking for a similar problem in 3-D. I had row and column indices and wanted to change all values corresponding to those indices, but in each page (so the entire 3rd dimension). Basically, I wanted to execute mtx(row(i),col(i),:) = 0;
, but without looping through the row and col vectors.
I thought I'd share my solution here instead of making a new question since it's closely related.
One other difference was that linear indices were available to me from the start because I was determining them using find
. I'll include that part for clarity's sake.
mtx = rand(100,100,3); % you guessed it, image data
mtx2d = sum(mtx,3); % this is similar to brightness
ind = find( mtx2d < 1.5 ); % filter out all pixels below some threshold
% now comes the interesting part, the index magic
allind = sub2ind([numel(mtx2d),3],repmat(ind,1,3),repmat(1:3,numel(ind),1));
mtx(allind) = 0;
精彩评论