Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: assign to matrix with column\row index pairs [duplicate]

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?

like image 568
olamundo Avatar asked Aug 19 '11 09:08

olamundo


1 Answers

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;
like image 107
olamundo Avatar answered Sep 20 '22 06:09

olamundo