Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort columns in Matlab

Tags:

matlab

I have 2 columns of data imported from using textscan. The data looks like this where U is undetect and D is detect

mydata=

.51 U
.57 D
.48 U
.47 D

 my data = [4x1 double]    [4x1 char]

I want to sort the data by the first column and so the data would look like this

.47  D
.48  U
.51  U    
.57  D

I would like to preserve the cell structure so that the following command to assign logical value still hold true:

c = zeros(size(mydata,1),1); % preallocate empty matrix 

c = mydata{2} == 'U';
for i = 1:size(mydata,1)
      curValue = mydata{i,2};
      data{i,3} =  ~isempty(curValue) && ischar(curValue) && strcmp(curValue ,'U');
end

I read about sortrows but the function is used to sort matrix containing just numbers.

Does anyone have a solution for sorting arrays with a mixture of numbers and characters.

like image 954
user1009166 Avatar asked Dec 23 '11 20:12

user1009166


2 Answers

You can SORT by one vector and apply the sorting index to another vector.

[mydata{1},idx] = sort(mydata{1});
mydata{2} =  mydata{2}(idx);
like image 169
yuk Avatar answered Oct 16 '22 15:10

yuk


I don't think you can directly sort the cell array, because each cell is considered a different "entity". You can always sort the numbers, use the indices to sort the characters, and then put it back in the cell array:

nums = mydata{1};
chars = mydata{2};
[~, ind] = sort(nums);
sortednums = nums(ind);
sortedchars = chars(ind);
mydata{1} = sortednums;
mydata{2} = sortedchars;
like image 33
3lectrologos Avatar answered Oct 16 '22 15:10

3lectrologos