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

2 ビュー (過去 30 日間)
Izabela Nowaczynska
Izabela Nowaczynska 2020 年 12 月 1 日
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

採用された回答

Mathieu NOE
Mathieu NOE 2020 年 12 月 1 日
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 件のコメント
Izabela Nowaczynska
Izabela Nowaczynska 2020 年 12 月 2 日
Thank you very much :)
Mathieu NOE
Mathieu NOE 2020 年 12 月 2 日
you're welcome !

サインインしてコメントする。

その他の回答 (1 件)

Rik
Rik 2020 年 12 月 1 日
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 件のコメント
Rik
Rik 2020 年 12 月 2 日
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 2020 年 12 月 3 日
No, thanks, that was my mistake.
Everythings work now :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by