In one loop, sort table and save each matrix in different text files, How?
1 view (last 30 days)
Show older comments
Dear,
I have a big table named sampleU (a simplified table is attached!), with 5 columnes. I would like to have a loop and based on unique values from column Z create matrix for each value and save them in separate text files with different names (U1, U2, U3,....untill U= last Z).
I am aiming for example get the U1 matrix as then save it as U1.txt
U1 =
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1234912/image.png)
So far i manage to have the data and unique values but having trouble reading each unique value in a loop and automatecly save them in different .txt files! (The loop is not correct in the code below)
Any suggestions?
data= SampleU % reading the excel table (I have added entire table as data table/ havent read it from Excel)
Z= unique (data.Z);
for ii = 1:Z ; %% need a loop to rad all unique values in Z column
U=?? %% maybe another loop for saving each unique value as U1, U2, U3...
U'ii'=data(data.Z ==Z,:); %%Sort out the sub-matrix as an example for Z=-2 is attached
print( '.txt'); %% Save the sub-matrix as a text
end
0 Comments
Accepted Answer
Voss
on 18 Dec 2022
Edited: Voss
on 18 Dec 2022
data = readtable('sampleU.xlsx')
[uZ,~,jj] = unique(data.Z);
for ii = 1:numel(uZ)
% pick a file name for the sub-table (note that %d may not be the
% best format, particularly if data.Z has some non-integer values):
file_name = sprintf('sampleU_z=%d.txt',uZ(ii));
% write the sub-table to file:
writetable(data(jj == ii,:),file_name);
end
% show the names of the new files:
dir('*.txt')
% check the contents of some of the resulting txt files:
t_test = readtable('sampleU_z=-1.txt')
t_test = readtable('sampleU_z=-2.txt')
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!