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

7 ビュー (過去 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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by