Complete matrix with vectors as indices in matlab

前端 未结 2 464
梦毁少年i
梦毁少年i 2021-01-27 00:47

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

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-27 01:49

    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;
    

提交回复
热议问题