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

조회 수: 8 (최근 30일)
Alfie Hunt
Alfie Hunt 2020년 4월 6일
댓글: Alfie Hunt 2020년 4월 7일
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

채택된 답변

James Tursa
James Tursa 2020년 4월 6일
편집: James Tursa 2020년 4월 6일
>> [~,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
Alfie Hunt
Alfie Hunt 2020년 4월 6일
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 2020년 4월 7일
Worked by using Table, thank you :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by