0

Suppose I have a cell array x and an integer array y:

x = {'apple', 'orange', 'banana', 'pear'};
y = [2 4 3 1];

In fact, y represents indices of x. I want to now create a cell array z with the elements of x reordered as specified by the order of these indices. This would give me:

z = {'orange', 'pear', 'banana', 'apple'};

Can I do this in one line without having to loop through each element and place it in z in turn?

Amro
  • 123,847
  • 25
  • 243
  • 454
Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • I've only tried a very exhaustive approach where I do the reordering myself in a loop, i.e. for each index in the new `z`, find the corresponding element in `x` by using the respective index from `y`, and inserting that into `z`. But I'm wondering if there is a way to do this in Matlab in just one line? – Karnivaurus Jun 26 '14 at 16:04
  • Sorry, downvoting. This is too basic Matlab (as is evident from [CST-link's answer](http://stackoverflow.com/a/24435337/2586922)). – Luis Mendo Jun 26 '14 at 16:08
  • 1
    I disagree, upvoting because I think this is useful: the indexing of cell arrays is a bit tricky for newcomers (i.e. when to use `{ind}` vs `(ind)`). Yes the docs (https://www.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html) quickly elucidate why it makes sense not to use curly brackets here, but I still think this question is specifically valuable. – MattG Nov 07 '18 at 21:12

1 Answers1

5

You can use an array as an array subscript:

x = {'apple', 'orange', 'banana', 'pear'};
y = [2 4 3 1]; 
z = x(y);

This code assigns creates a cell array z that contains the elements from x, that are selected by the indices y, in the order of the indices. (that is the basics of MATLAB subscripting; other methods of indexing are linear and logical, see Mathworks site for details).

Paul Wintz
  • 2,542
  • 1
  • 19
  • 33