How do I declare multiple variables with a rule for naming?
Show older comments
If I want to do something like this:
A41 = B(4,1);
A42 = B(4,2);
A43 = B(4,3);
A31 = B(3,1);
A32 = B(3,2);
A33 = B(3,3);
or something like this:
B(1,1) = A11;
B(1,2) = A12;
B(1,3) = A13;
B(1,4) = A14;
Is there a one- or two-liner way of doing this pattern? Can you automate variable naming? Can you do something like passing the names of variables as inputs to functions?What is the best paradigm in MATLAB for this kind of thing altogether?
1 Comment
Stephen23
on 29 Oct 2023
"Is there a one- or two-liner way of doing this pattern?"
Yes, if you want to force yourself into writing slow, complex, inefficient, obfuscated buggy code that is harder to debug.
"Can you automate variable naming?"
I could.... but I would not.
"Can you do something like passing the names of variables as inputs to functions?"
Sure... but then trying to access that variable will be slow and complex. Best avoided.
The MATLAB documentation clearly states that the recommended day to pass data to functions is as input/output arguments:
Passing input/output arguments is the most efficient and most robust approach by far. So far you have not given any reason why you cannot do this.
"What is the best paradigm in MATLAB for this kind of thing altogether?"
The best paradigm is to use matrices/arrays and indexing. It is even in the name: "MATLAB" comes from "MATrix LABoratory" and not from "lets dynamically name lots of variables in the workspace and make processing the data harder". The paradigm that you are attempting is so bad that there is an entire page of the documentation speicifically advising against it, which states "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended."
So now you have both the MATLAB documentation and also experienced MATLAB users telling you to avoid your approach:
Accepted Answer
More Answers (0)
Categories
Find more on Introduction to Installation and Licensing 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!