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

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

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