Let us say that we have a matrix A1 and two vectors v1 and v2 as follow:
A1=zeros(5, 5);
v1=[1 2 3];
v2=[5 5 4];
Is there a way to replace the
Convert your vectors into linear indices:
A1=zeros(5, 5);
v1=[1 2 3];
v2=[5 5 4];
ind=sub2ind(size(A1), v1, v2);
A1(ind(1))=1
A1 =
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
etc.
Basically you have row and column information and need to convert them into a linear index, to index into A1
. For this, use sub2ind -
A1(sub2ind(size(A1),v1(1),v2(1))) = 12
A1(sub2ind(size(A1),v1(2),v2(2))) = 10
A1(sub2ind(size(A1),v1(3),v2(3))) = 9
Output -
A1 =
0 0 0 0 12
0 0 0 0 10
0 0 0 9 0
0 0 0 0 0
0 0 0 0 0
If you have those values stored in some array, array1
, use this for the same result as above -
array1 = [12 10 9];
A1(sub2ind(size(A1),v1,v2)) = array1;