9

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

I have a matrix A and three vectors of the same length, r, holding the indexes of the rows to assign to, c, holding the indexes of the columns to assign to, and v containing the actual values to assign.

What I want to get is A(r(i),c(i))==v(i) for all i. But doing

A(r,c)=v;

Doesn't yield the correct result as matlab interprets it as choosing every possible combination of r and c and assigning values to it, for instance

n=5;
A=zeros(n);
r=1:n;
c=1:n;

A(r,c)=1;

Yields a matrix of ones, where I would like to get the identity matrix since I want A(r(i),c(i))==1 for each i, that is only elements on the diagonal should be affected.

How can I achieve the desired result, without a for loop?

Community
  • 1
  • 1
olamundo
  • 23,991
  • 34
  • 108
  • 149
  • similar question: [Converting a matlab matrix to a vector](http://stackoverflow.com/questions/1931545/converting-a-matlab-matrix-to-a-vector) – Amro Aug 19 '11 at 22:16
  • 1
    @Amro - While I agree the answers to both questions are very similar, the questions are different - I wanted to know how to assign to a matrix, while the other question wants to know how to covert a matrix into a vector. One wouldn't reach the other question when looking for an answer to my question. – olamundo Aug 21 '11 at 11:25
  • 1
    I did not down-vote you, I simply linked to the other question as being similar (as opposed to voting to close as duplicate).. – Amro Aug 21 '11 at 14:17
  • possible duplicate of [How can I change the values of multiple points in a matrix?](http://stackoverflow.com/q/6850368/52738) – gnovice Mar 26 '12 at 13:50

1 Answers1

16

OK, I've found the answer - one needs to use linear indexing, that is convert the column\row pairs into a single index:

idx = sub2ind(size(A), r,c);
A(idx)=v;
olamundo
  • 23,991
  • 34
  • 108
  • 149