matlab - sorting cell array based on column (double not char) values -


i have 3x1 cell array includes:

10.2   15.2   7.2    

and 3x1 cell array b includes:

m l s 

i join these new 3x2 cell array c including:

10.2  m 15.2  l 7.2   v 

then want sort c according values of first column supposed be

7.2 v 10.2 m 15.2 l 

what did far follows:

c=a; c(:,2)=b; c=sortrows(c,1); 

however result is:

10.2 m 15.2 l 7.2 v 

i think reason considers numbers in first column characters , way sorts them looking @ digits of each number 1 one left.. 10.2 less 7.2.
looking way assign numbers numbers c when sort them considers them numbers not characters. tried use cell2mat when assigning , b c did not work. have searched web not find looking for.

thank you!

this need:

>> c = cell(numel(a),2); [sorted_a, index_a] = sort(cell2mat(a)); c(:,1) = num2cell(sorted_a); c(:,2) = b(index_a); 

for example, input follows:

>> = {10.2; 15.2; 7.2}; b = {'m'; 'l'; 'v'}; 

the result be:

>> c  c =       [ 7.2000]    'v'     [10.2000]    'm'     [15.2000]    'l' 

edit

it seems in case, input array a not cell array of numbers, cell array of strings; i.e., example,

>> = {'10.2'; '15.2'; '7.2'}; 

in case, need make following changes:

  1. use str2double(a) instead of cell2mat(a)
  2. use strtrim(cellstr(num2str(sorted_a))) instead of num2cell(sorted_a);

your final code be:

>> c = cell(numel(a),2); [sorted_a, index_a] = sort(str2double(a)); c(:,1) = strtrim(cellstr(num2str(sorted_a))); c(:,2) = b(index_a); 

for example, input follows:

>> = {'10.2'; '15.2'; '7.2'}; b = {'m'; 'l'; 'v'}; 

the result be:

>> c  c =       '7.2'     'v'     '10.2'    'm'     '15.2'    'l' 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -