2

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;
gnovice
  • 125,304
  • 15
  • 256
  • 359
thron of three
  • 521
  • 2
  • 6
  • 19
  • I disagree that this is an exact duplicate of the above linked question. While the solutions will use the same approach, this one involves *assignment to* a matrix, not *indexing from* a matrix, so having a separate question for each makes sense. – gnovice Mar 26 '12 at 13:56
  • @gnovice I vote for removing the other question as it is phrased worse than this one. I do not agree that the difference between accessing and assignment merits two separate questions. – Shai Dec 05 '12 at 16:21

3 Answers3

7

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;
thron of three
  • 521
  • 2
  • 6
  • 19
gnovice
  • 125,304
  • 15
  • 256
  • 359
1

Another answer:

mtx(co_ords(1,:)+(co_ords(2,:)-1)*500)=0;
Junuxx
  • 14,011
  • 5
  • 41
  • 71
shangping
  • 989
  • 2
  • 9
  • 25
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;
scenia
  • 1,609
  • 14
  • 33