npisinp
npisinp

Reputation: 370

Complete matrix with vectors as indices in matlab

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 elements of A1 using v1 and v2 as indices one by one? i.e., insert in A1(1, 5), A1(2, 5), and in A1(3, 4) some elements.

The following do all combinations of v1 and v2. I want only one by one. i.e., v1(1) with v2(1), v1(2) with v2(2), and so on.

A1(v1, v2) 

Upvotes: 1

Views: 75

Answers (2)

Divakar
Divakar

Reputation: 221684

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;

Upvotes: 2

Cape Code
Cape Code

Reputation: 3574

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.

Upvotes: 1

Related Questions