For loop for unequal increment

조회 수: 2 (최근 30일)
DEBABRATA PALAI
DEBABRATA PALAI 2020년 1월 26일
댓글: Weird Rando 2020년 1월 26일
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
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
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
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:

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by