Create Variables in loop

조회 수: 5 (최근 30일)
Katy Weihrich
Katy Weihrich 2018년 5월 9일
댓글: Jan 2018년 5월 9일
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
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
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
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by