A loop that saves the data from the inner loop as next file
2 views (last 30 days)
Show older comments
Izabela Nowaczynska
on 1 Dec 2020
Commented: Izabela Nowaczynska
on 3 Dec 2020
I have data from 1 to 148 (table tw1). The script choose window of 20 lines (from 1 to 20) save this as file (Window_1_20.txt) . After that selects the next 20 lines (2-21) and save this data as next file (Window_2_21).
The loop will end after last window of data (128-148) will be saved as file.
I'm not sure the proper order of the loops.
Below is my code (it's pretty basic but i'm not a pro)
h=1;
l=h+1:128;
k=l+20;
for i=l:k
fid=fopen(FileName);
for w=i:k
BaseName='Window_';
fprintf(fid, '%04d, %04d, %04d', tw1(w,1), tw1(w,2), tw1(w,3))
FileName=[BaseName,num2str(w)];
end
fclose(fid);
end
0 Comments
Accepted Answer
Mathieu NOE
on 1 Dec 2020
hello
this is my suggestion - only one loop
the code works whatever the dimensions of the data (tw1)
you can also easily change the number of lines to store in each file
hope it helps
tw1 = rand(148,3); % dummy data
lines = 20; % number of lines to store in each file
[m,n] = size(tw1);
for ci = 1 :m-lines+1
ind_start = ci;
ind_stop = ind_start+lines-1;
data = tw1(ind_start:ind_stop,:);
FileName = [BaseName,num2str(ci)];
writematrix(data, FileName, 'FileType','text');
end
6 Comments
More Answers (1)
Rik
on 1 Dec 2020
There are several issues with your code. I will attempt to fix most of them below.
%create some random data
tw1=rand(148,3);
BaseName='Window_';
WindowWidth=20;
for n1=1:(size(tw1,1)-WindowWidth)
n2=n1+WindowWidth-1;
FileName=sprintf('Window_%d_%d',n1,n2);
fid=fopen(FileName,'w');
for k=n1:n2
fprintf(fid, '%04d, %04d, %04d', tw1(k,1), tw1(k,2), tw1(k,3));
end
fclose(fid);
end
3 Comments
Rik
on 2 Dec 2020
I used your format specifier. I assumed you had read the documentation for fprintf and the missing \n was on purpose.
Also, did you replace my randomly generated data with your own?
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!