Problems with sortrows and str2double, why is it still string?

6 views (last 30 days)
I have a matrix with two columns: respiration value and respiration phase (e.g. 45216 | ExhaleOnset)
I initially had trouble with sorting matrix rows by numerical value in the first column using sortrows, as values were not ordered by numerical value, rather their string value. Therefore, using str2double should fix this issue? It works when one column is isolated, but when re-merged with respiration phase label it has a str order (example below)
Example of code
%Creates matrix by respiration label (in that order)
Respiration_Labelled = [Sorted_ExhaleOnsets;Sorted_ExhaleOffsets;Sorted_InhaleOnsets;Sorted_InhaleOffsets;Sorted_Peaks;Sorted_Troughs];
%seperate the columns
Respiration_Values = (Respiration_Labelled(:,1)); %seperate respvalues
Respiration_Strings = (Respiration_Labelled(:,2)); %isolate respiration phase labels
Respiration_Numbers = str2double(Respiration_Values); %convert from str to double
Respiration_Events = [Respiration_Numbers,Respiration_Strings]; %merge
%Now to sort
B = sortrows(Respiration_Events,1);
However, the problem still persists .. Example
"1391415" "exhaleOnsets"
"1392219" "Troughs"
"1392550" "exhaleOffsets"
"1392551" "InhaleOnsets"
"139299" "Troughs"
"1393054" "Peaks"
"1393649" "inhaleOffsets"
It works when sortrows is used only for Respiration_Numbers, how do I prevent converting to string when creating the matrix?
Thanks in advance

Accepted Answer

James Tursa
James Tursa on 6 Apr 2020
Edited: James Tursa on 6 Apr 2020
>> [~,x] = sort(str2double(Respiration_Values));
>> B = Respiration_Labelled(x,:)
B =
7×2 string array
"139299" "Troughs"
"1391415" "exhaleOnsets"
"1392219" "Troughs"
"1392550" "exhaleOffsets"
"1392551" "InhaleOnsets"
"1393054" "Peaks"
"1393649" "inhaleOffsets"
Your current method is failing because in your merge line, the concatenation forces all of the stuff inside to be converted to the same type. So everything gets put back into the string type. If you really need one column to be numeric and another column to be string, you would need another method to store them as a combined type, such as a cell array or a table.
  2 Comments
Alfie Hunt
Alfie Hunt on 6 Apr 2020
Yes, I need one column to be numeric and another to be string. Can I simply create a cell array with the variables I've created already, or would i need to prepare it in some other way?

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!