MATLAB: How to order values within a cell array more efficiently?

cell arraysloopsordering

I have a 3×12 cell array called "ratings"
ratings= {'AAA','AA','A','A-','BBB-','BB+','BB','BB-','B+','B','B-','CCC+';
'A','A-','AA','AAA','B','B+','B-','BB','BB+','BB-','BBB-','CCC+';
1,1,1,3,11,16,18,1,1,17,16,14};
  • The first row of the array has the ratings in the desired order
  • The second row has the ratings disordered
  • The third row contains a number associated with the ratings in the second row
I wrote the following code:
orderedratings=cell(1,length(ratings))
for i=1:length(ratings);
for j=1:length(ratings)
if strcmp(ratings(1,i),ratings(2,j))==1
orderedratings(i)=ratings(3,j);
end
end
end
and it allows me to reorder the third row in respect to the ordered first row, such that:
orderedratings={1,6,8,2,18,3,1,21,17,12,10,1}
Is there a way to do the same more efficiently, or another way without "for" conditionals?? It is very much appreciated a different appoach.
Antonio Espana

Best Answer

The following should work regardless of the ordering of the two rows:
[~,idx] = ismember(ratings(1,:),ratings(2,:));
orderedratings = ratings(3,idx)