Get textscan to sort the rows as matrices and columns as cells

5 views (last 30 days)
I have a text file with 1151 lines and each line is comma separated with 20 numbers, like this:
@data
1,1,22,22,22,19,18,14,49.895756,17.775994,5.27092,0.771761,0.018632,0.006864,0.003923,0.003923,0.486903,0.100025,1,0
1,1,24,24,22,18,16,13,57.709936,23.799994,3.325423,0.234185,0.003903,0.003903,0.003903,0.003903,0.520908,0.144414,0,0
...
When I open a textfile with this code:
% Import data %
fid = fopen('assignment1.txt', 'r'); %Open text file
if fid == -1 %If failed to open
disp('Error, check file name') %Display error message
else
%Imports all the text to a cell array
fmt = repmat('%f', 1, 20);
S = textscan(fid, fmt, 'Delimiter', ',', 'CommentStyle', '@');
end
I get a 1x20 cell array, where each entry is a 1151x1 double matrix.
I want it to be a 1x1151 cell array with 20x1 matrices instead. I want it that way because I need to randomly swap the positions of the rows between each other, not the columns.

Accepted Answer

Stephen23
Stephen23 on 23 Jun 2020
opt = {'Delimiter',',', 'CommentStyle','@', 'CollectOutput',true};
[fid,msg] = fopen('assignment1.txt','rt');
assert(fid>=3, msg)
%Imports all the text to a cell array
fmt = repmat('%f', 1, 20);
C = textscan(fid, fmt, opt{:});
fclose(fid);
C = num2cell(C{1},2);

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!