How can I change the values of multiple points in a matrix?

夙愿已清 提交于 2019-12-17 03:44:12

问题


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;

回答1:


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;



回答2:


Another answer:

mtx(co_ords(1,:)+(co_ords(2,:)-1)*500)=0;



回答3:


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;


来源:https://stackoverflow.com/questions/6850368/how-can-i-change-the-values-of-multiple-points-in-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!