Create Variables in loop
1 回表示 (過去 30 日間)
古いコメントを表示
I have a large dataset and need to load it into chunks and sort it into different files. So I start out with the first part of my raw data and sort it into binary User 1, User 2, User 3, ... files. For this purpose I created a user loop. I first use fopen, then load the current chunk of raw data, then run the user loop, then use fwrite, then load the next chunk till the data sorting is done and cloase all the user flies (fclose).
So far I have written out:
x = 1;
while x <= length(userlist_long_day)
if x == 1
username_1 = userlist_long_day(x,:);
filename_1 = [dir_B_E_PD_Day SLASH 'Output_Day' date_name, '_ID' username_1 '_data' fileending];
fid_1 = fopen(filename_1,'wb','ieee-be');
end
...
...
end
for all of my users. But it makes the code pretty dense and it is very annoying having to change every single User every time I want to change my saving format (I have at least 6 different files to open, write and close for each user). I wanted to change the variable names in a loop but saw that it is not advisable. Does someone know an alternative that I could use?
1 件のコメント
Stephen23
2018 年 5 月 9 日
編集済み: Stephen23
2018 年 5 月 9 日
"But it makes the code pretty dense and it is very annoying having to change every single User every time I want to change my saving format..."
Yes, I would imagine it is.
"I wanted to change the variable names in a loop but saw that it is not advisable"
The MATLAB documentation specifically advises against doing this. As do all experienced MATLAB users.
"Does someone know an alternative that I could use?"
Yes! In one word: indexing. Indexing is neat, simple, easy to debug, and very efficient. Indexing is what you should use, either with one struct array, or two cell arrays and numeric array.
採用された回答
Image Analyst
2018 年 5 月 9 日
As you already know, this is not advisable. What you could do is to use a single structure array:
for k = 1 : 6
userInfo(k).userName = userlist_long_day(x,:);
userInfo(k).fileName = [dir_B_E_PD_Day SLASH 'Output_Day' date_name, '_ID' username_1 '_data' fileending];
userInfo(k).fid = fopen(filename_1,'wb','ieee-be');
etc.
You could also use 3 different cell arrays
1 件のコメント
Jan
2018 年 5 月 9 日
+1. In addition:
- Use fullfile instead of the horizontal concatenation [] ans teh variable SLASH. This is safer and independent from the platform.
- The operating system limits the number of files, which can be open at the same time. A usual limit is 256 files. So remember to use fclose as soon as possible to avoid unexpected errors. Always check igf the output of fopen is -1 to catch problems.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!