MATLAB: How to sort each line in a text file by the first character in a line

matlab text filesorting lines

how do I get a switch case loop that reads a text file line by line and sorts the lines by the beginning character in each line? I need to use a switch case to account for four different characters. I'm using the fgetl function to read the file line by line so now I just need to figure out how to sort the lines by the beggining character. Once I can sort them I will likely store them in different variables.

Best Answer

The data you posted is a bit difficult to work with, so I created my own version that should work with it. It assumes your data are in a cell array.
Try this:
C = {'G34 706.0461e-003 823.4578e-003 438.7444e-003 489.7644e-003 276.0251e-003'
'G34 31.8328e-003 694.8286e-003 381.5585e-003 445.5862e-003 679.7027e-003'
'R01 276.9230e-003 317.0995e-003 765.5168e-003 646.3130e-003 655.0980e-003'
'R01 46.1714e-003 950.2220e-003 795.1999e-003 709.3648e-003 162.6117e-003'
'R01 97.1318e-003 34.4461e-003 186.8726e-003 754.6867e-003 118.9977e-003'};
FC = cellfun(@(x)x(:,1), C); % Get First Letters
[Cu,~,idx] = unique(FC, 'stable'); % Unique Letters % Indices
Sorted = accumarray(idx, (1:numel(idx)).', [], @(x){C(x)}); % Separate By First LEtter Into Each Cell Of ‘Sorted’
OutG = Sorted{1} % Display Result

OutR = Sorted{2} % Display Result
producing:
OutG =
2×1 cell array
{'G34 706.0461e-003 823.4578e-003 438.7444e-003 489.7644e-003 276.0251e-003'}
{'G34 31.8328e-003 694.8286e-003 381.5585e-003 445.5862e-003 679.7027e-003' }
OutR =
3×1 cell array
{'R01 276.9230e-003 317.0995e-003 765.5168e-003 646.3130e-003 655.0980e-003'}
{'R01 46.1714e-003 950.2220e-003 795.1999e-003 709.3648e-003 162.6117e-003' }
{'R01 97.1318e-003 34.4461e-003 186.8726e-003 754.6867e-003 118.9977e-003' }
This should work with your data. It is not restricted to simply those letters you posted, and can work with amy set.
.
Related Question