For loop for unequal increment
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi,
I have some .txt files having name--B1_0_B1_1, B3_0_B3_1, B6_0_B6_1.. I wrote the following loop for loading all this data file in matlab.
But the problem is with this code it cant load the files due to having unequal increment of file number.. can anybody help me to sort out this problem?
댓글 수: 2
Stephen23
2020년 1월 26일
Using numbered variables is a sign that you are doing something wrong.
Accessing numbered variables in a loop is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
In contrast indexing is neat, simple, easy to debug, and very efficient (unlike what you are trying to do).
Weird Rando
2020년 1월 26일
I would make 2 changes to the code.
file_B = dir('D:\Maldi related\Data\23012020\data\*.txt');
load(file_B(a).name);
답변 (1개)
Stephen23
2020년 1월 26일
편집: Stephen23
2020년 1월 26일
You are confusing two different ways of defining filenames. Currently you use dir to get the actual filenames from the OS, but then you ignore those names completely and try to generate the filenames using string concatenation. Complicated, and a waste of the (perfectly correct) filenames that you asked the OS to give you!
You should just use dir like this:
D = 'path to the directory where the files are saved';
S = dir(fullfile(D,'*.txt'));
for k = 1:numel(S)
F = fullfile(D,S(k).name);
S(k).data = dlmread(F); % DLMREAD is probably a better choice than LOAD.
end
All of the imported file data will be in the non-scalar structure S, which you can easily access using indexing:
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!