Problems with sortrows and str2double, why is it still string?
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alfie Hunt
el 6 de Abr. de 2020
Comentada: Alfie Hunt
el 7 de Abr. de 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
0 comentarios
Respuesta aceptada
James Tursa
el 6 de Abr. de 2020
Editada: James Tursa
el 6 de Abr. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!