Access variables with naming in workspace

6 ビュー (過去 30 日間)
Miraboreasu 2022 年 9 月 14 日
コメント済み: Walter Roberson 2022 年 9 月 14 日
I have a workspce full of data1, data2, data3.....,data100
They are all arrays with (1,n)
Instead of do it one by one via
How can I use a loop to form this matrix
  1 件のコメント
Stephen23 2022 年 9 月 14 日
編集済み: Stephen23 2022 年 9 月 14 日
"I have a workspce full of data1, data2, data3.....,data100"
Having lots of numbered variables in the workspace is a sign that you are doing something wrong.
You did not tell us the most important information: how did you get all of these arrays into the workspace? The point where they are imported or created would be the correct place to fix your code, rather than what you are trying to do.
Whatever you do, do NOT use EVAL, ASSIGNIN, or follow any other subpar advice of that kind.



Stephen23 2022 年 9 月 14 日
This appears to be a follow up from your question from seven hours ago:
The best solution by far is to not get into the situation where you have lots of numbered variables in the workspace:
For example, you can easily LOAD into an output variable, which makes your data very easy to access (unlike what you are doing now) It assumes exactly one variable per MAT file.
N = 25;
C = cell(1,N);
for k = 1:N
F = sprintf('data%d.mat',k);
C(k) = struct2cell(load(F));
All of your imported filedata wll be in the cell array C. Note that you can trivially loop over all of C, or access its contents individually. For example, the data for the second file:

その他の回答 (1 件)

Chunru 2022 年 9 月 14 日
First of all, try to change the program that produces data1 to data100 by using multidimensional array or cell array if possible.
If that is not feasible for any reason, you can use eval:
matr = zeros(100, n)
for i=1:100
matr(i,:) = eval("data"+i)
  7 件のコメント
Walter Roberson
Walter Roberson 2022 年 9 月 14 日
There is no point teaching someone to use eval until they have actually encountered a situation that could not avoid using eval.



Find more on Variables in Help Center and File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by