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

11 vues (au cours des 30 derniers jours)
Alfie Hunt
Alfie Hunt le 6 Avr 2020
Commenté : Alfie Hunt le 7 Avr 2020
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

Réponse acceptée

James Tursa
James Tursa le 6 Avr 2020
Modifié(e) : James Tursa le 6 Avr 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 commentaires
Alfie Hunt
Alfie Hunt le 6 Avr 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?
Alfie Hunt
Alfie Hunt le 7 Avr 2020
Worked by using Table, thank you :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by