For loop for unequal increment

24 ビュー (過去 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 Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by