Access variables with naming in workspace
古いコメントを表示
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
```
matr(1,:)=data1
matr(2,:)=data2
etc
```
How can I use a loop to form this matrix
1 件のコメント
"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.
採用された回答
その他の回答 (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)
end
7 件のコメント
Stephen23
2022 年 9 月 14 日
Reading this user's last question informs us that their bad data design is easy to avoid.
It would help both the OP and future readers of this forum, to avoid dynamically named variables.
Rik
2022 年 9 月 14 日
I have not seen a situation 'in the wild' where eval could not be avoided. I don't see a reason why you would mention eval in this thread. You only risk teaching new users eval.
The only situation I have seen is when defining anonymous functions in an m file that Matlab 6.5 can also run.
Chunru
2022 年 9 月 14 日
Every thing has a use under certain circumstances, "eval" and "assign" and "load" included, though you may want to avoid them in most times. This should be a good advice for life in general.
Stephen23
2022 年 9 月 14 日
"...using other people's program (which you may have p code only) or you really don't want to spend time to change that program (good or bad)."
By reading the OPs previous questions we can see that (just like in 99.99% of situations involving attempts to access variable names) the OP simply painted themselves into a corner. As such, this OP's situation is easily avoided.
Chunru
2022 年 9 月 14 日
In my post, I have advised "First of all, try to change the program that produces data1 to data100 by using multidimensional array or cell array if possible".
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.
カテゴリ
ヘルプ センター および File Exchange で Variables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!