Map function in MATLAB?

前端 未结 7 841
情书的邮戳
情书的邮戳 2020-11-29 17:11

I\'m a little surprised that MATLAB doesn\'t have a Map function, so I hacked one together myself since it\'s something I can\'t live without. Is there a better version out

7条回答
  •  日久生厌
    2020-11-29 17:56

    A rather simple solution, using Matlab's vectorization would be:

    a = [ 10 20 30 40 50 ]; % the array with the original values
    b = [ 10 8 6 4 2 ]; % the mapping array
    c = zeros( 1, 10 ); % your target array
    

    Now, typing

    c( b ) = a
    

    returns

    c = 0    50     0    40     0    30     0    20     0    10
    

    c( b ) is a reference to a vector of size 5 with the elements of c at the indices given by b. Now if you assing values to this reference vector, the original values in c are overwritten, since c( b ) contains references to the values in c and no copies.

提交回复
热议问题