Matlab: assign to matrix with column\row index pairs
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;
Related videos on Youtube
olamundo
Updated on June 04, 2022Comments
-
olamundo 12 monthsPossible Duplicate:
How can I change the values of multiple points in a matrix?I have a matrix
Aand 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, andvcontaining the actual values to assign.What I want to get is
A(r(i),c(i))==v(i)for alli. But doingA(r,c)=v;Doesn't yield the correct result as matlab interprets it as choosing every possible combination of
randcand assigning values to it, for instancen=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))==1for eachi, that is only elements on the diagonal should be affected.How can I achieve the desired result, without a
forloop?-
olamundo almost 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 almost 12 yearsI did not down-vote you, I simply linked to the other question as being similar (as opposed to voting to close as duplicate)..
-