A loop that saves the data from the inner loop as next file

2 vues (au cours des 30 derniers jours)
Izabela Nowaczynska
Izabela Nowaczynska le 1 Déc 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

Réponse acceptée

Mathieu NOE
Mathieu NOE le 1 Déc 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 commentaires
Izabela Nowaczynska
Izabela Nowaczynska le 2 Déc 2020
Thank you very much :)
Mathieu NOE
Mathieu NOE le 2 Déc 2020
you're welcome !

Connectez-vous pour commenter.

Plus de réponses (1)

Rik
Rik le 1 Déc 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 commentaires
Rik
Rik le 2 Déc 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?
Izabela Nowaczynska
Izabela Nowaczynska le 3 Déc 2020
No, thanks, that was my mistake.
Everythings work now :)

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by