For loop for unequal increment

2 Ansichten (letzte 30 Tage)
DEBABRATA PALAI
DEBABRATA PALAI am 26 Jan. 2020
Kommentiert: Weird Rando am 26 Jan. 2020
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 Kommentare
Stephen23
Stephen23 am 26 Jan. 2020
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 am 26 Jan. 2020
I would make 2 changes to the code.
file_B = dir('D:\Maldi related\Data\23012020\data\*.txt');
load(file_B(a).name);

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen23
Stephen23 am 26 Jan. 2020
Bearbeitet: Stephen23 am 26 Jan. 2020
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:

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by