Search code examples
arraysmatlab

How to assign values from vector to matrix in Matlab


Suppose we have matrix of indices A=[1,3;2,1] and array/cell array/struct/table of values

  • B=[10,20,30] or B=[10;20;30]
  • C={'aa';5;"g"}
  • D is 3x1 or 1x3 struct array with fields: values and D(ii).values is 1x1 numeric array. vertcat(D.values)=[21;22;23]

I want to get new array/cell array/string array with same size as A and filled with values from B,C, or D from the postions given in A

  • b=foo(A,B) returns b=[10,30;20,10]
  • c=bar(A,C) returns c={'aa',"g";5,'aa'}
  • d=foobar(A,D.values) returns d=[21,23;22,21]

I can do it with for loops but with arrays of 2000x2000 it is terribly inefficient. Is there a way to approach it faster?


Solution

  • You can just use A for indexing, the output array will be the same shape as the indexing array:

    A=[1,3;2,1]; B=[10,20,30]; C={'aa';5;"g"};
    
    b = B(A);
    c = C(A);
    

    You can handle d the same way as b if you make an intermediate array from D(:).values:

    d = [D(:).values];
    d = d(A);
    

    Or do it directly as suggested by Bill in the comments, but you have to reshape because the shape isn't preserved when indexing a structure

    d = reshape( [D(A).values], size(A) );
    

    outputs