Sort columns in matlab

I have 2 columns of data imported from textscan. The data looks like this: U undetect and D detects

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 will look like this:

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

I would like to save the cell structure so that the following command to assign a boolean value is saved:

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 sorts, but the function is used to sort a matrix containing only numbers.

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

+5
source share
2 answers

You can SORT with one vector and apply the sort index to another vector.

[mydata{1},idx] = sort(mydata{1});
mydata{2} =  mydata{2}(idx);
+8

, , "". , , :

nums = mydata{1};
chars = mydata{2};
[~, ind] = sort(nums);
sortednums = nums(ind);
sortedchars = chars(ind);
mydata{1} = sortednums;
mydata{2} = sortedchars;
+2

All Articles