简体   繁体   中英

Matlab - Using matrix as an index for array vectors

I currently have a vector containing a cell array of predefined values. The number and content of these values should be able to vary:

names = {'r1','r2','r3'};

Furthermore, I have a Matrix, that should serve as an index Matrix. It looks like the following example, however, should also be variable in its size.

mat = [1 3 3; 2 1 3; 1 1 1];

Delivering:

 1  3  3 
 2  1  3 
 1  1  1 

I would now like to create a matrix containing the respective values of the array in the same matrix format. Hence, whereever mat contains a 1 the output should contain the first value of names and so on. The final result should then look like:

r1  r3  r3 
r2  r1  r3 
r1  r1  r1 

Just to avoid missunderstandings: The content of names simply serves as an example here. Later specific names should be matched and it cannot be solved by simply adding an r infront of every index value.

Many thanks for your help!

That's simple:

result = names(mat);

The only caveat is that every numeric element in mat must be integer and between 1 and the number of elements in names .

Explanation: The mat works as a linear index . The general rule when indexing linearly is that the values are taken from the source array in column order (as it is normal), but the shape is the same as the shape of the index array.

Later Edit , thanks to Luis Mendo : this rule is valid except for the singleton dimensions of the index array. To enforce the rule for this corner case, one may use the slightly more elaborate (and more time-consuming) form:

result = reshape(names(mat), size(mat));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM