Import multiple .text matrices in array

1 回表示 (過去 30 日間)
IGArg
IGArg 2019 年 12 月 4 日
編集済み: Jakob B. Nielsen 2019 年 12 月 5 日
I have a set of multiple (hundreds) matrix in .text format, and I need to import them in MATLAB for different kind of analysis.
Because the steps I need to take are the same foreach matrix, I would like to save all of them in an array, in order to use for loops in a function.
At the moment I'm only able to import each of them in the workspace individually doing:
files = dir('*.txt');
for i=1:length(files)
eval(['load ' files(i).name ' -ascii']);
end
In this way I only obtain hundreds of matrices with different names in the workspace, which is very bad to work with.
What is the best way to import the matrices and directly put them inside an array?
  2 件のコメント
Stephen23
Stephen23 2019 年 12 月 4 日
編集済み: Stephen23 2019 年 12 月 4 日
You should not use eval like that, it is simpler and more reliable to call load as a function:
S = load(files(i).name,'-ascii');
IGArg
IGArg 2019 年 12 月 4 日
Thank you!

サインインしてコメントする。

採用された回答

Jakob B. Nielsen
Jakob B. Nielsen 2019 年 12 月 4 日
編集済み: Jakob B. Nielsen 2019 年 12 月 5 日
Do you have experience working with structures? In your workspace there will be only one item, which makes keeping the overview much easier.
for i=1:length(files)
YourStructure(i).matrix=load(files(i).name,'-ascii');
YourStructure(i).name=files(i).name
end
YourStructure(3).matrix %<-- you call it this way, where the indexing is now in the structure. This particular case it will call the 3rd entry in the structure.
  2 件のコメント
IGArg
IGArg 2019 年 12 月 4 日
編集済み: IGArg 2019 年 12 月 4 日
Actually trying to implement this solution I get an error. Apparently it's not possible to associates to a variable (or the entry of a structure) the value returned by eval.
It's like eval can only generate a variable but not directly associate it to another, so I still have the problem of how to actually fill the structure (just as I would have for arrays).
UPDATE: Using the load function alone without eval works fine in your solution, thanks for your reply!
Stephen23
Stephen23 2019 年 12 月 4 日
編集済み: Stephen23 2019 年 12 月 4 日
Simpler, neater, less buggy, and easier to debug without eval:
YourStructure(i).matrix = load(files(i).name,'-ascii');
eval should be avoided for such trivial code:

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by