Change variable name based on what loop it is on
显示 更早的评论
I have a user input a vector for the variable titled 'k1'. A loop is set up where the input conditions are the same, but the variable name must be changed in order to perform some operations and store the data. I would like it to change based on which loop it is performing, like k1 might be given the name k2 on the second loop. I don't know how I could do this simply or if doing this is possible.
1 个评论
"I don't know how I could do this simply or if doing this is possible."
It is possible, but is best avoided:
The neat, simple, robust, reliable, efficient alternative is to use indexing. You should use indexing.
采纳的回答
更多回答(2 个)
Walter Roberson
2025-4-14
编辑:Walter Roberson
2025-4-14
0 个投票
It is possible to do this.
It is not possible to do this simply.
We firmly recommend that you do not do this.
dpb
2025-4-14
0 个投票
While it can be done, it almost never should be the way..."there be dragons!" and slow, obfuscated and very difficult to debug code. See <Do not use globals or eval>. The direct link is to @Matt Fig's answer, but the overall discussion/thread is informative and valuable. The offcial Mathworks documentation link <Alternaives to the eval Function> discusses exactly the thing you mention as its first use case...
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!