Matlab: assign to matrix with column\row index pairs

11,700

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;
Share:
11,700

Related videos on Youtube

olamundo
Author by

olamundo

Updated on June 04, 2022

Comments

  • olamundo
    olamundo almost 2 years

    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?

    • olamundo
      olamundo over 12 years
      @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.
    • Amro
      Amro over 12 years
      I did not down-vote you, I simply linked to the other question as being similar (as opposed to voting to close as duplicate)..