Clear Filters
Clear Filters

use assignin within a function

14 views (last 30 days)
Oliver Warlow
Oliver Warlow on 1 Jul 2013
I want to create variable names automatically within a function (which are then used within this same function) that has been called by a script. As far as I am aware assign is unable to define variables within the workspace of the function.
Is there any neat solution to get round this? I do have a workaround but it is not very elegant. thanks Oli

Answers (2)

Matt J
Matt J on 1 Jul 2013
Edited: Matt J on 1 Jul 2013
You would use EVAL instead, but it is a bad idea to inexplicitly assign variables, whether by EVAL, ASSIGNIN, LOAD or whatever. Use dynamic fieldnames instead
S.('name1')=val1;
S.('name2')=val2;
etc... See also
and

Jan
Jan on 1 Jul 2013
This is a very frequently asked question, and the answer is easy: Do not do this. See FAQ: How can I create A1, A2, ... in a loop
Creating variables dynamically creates more problems as it solves. Beside the substantial decrease of the speed, the dugging is the main problem: It is hard to impossible to find out, what the program is doing when you read the code.
  2 Comments
Oliver Warlow
Oliver Warlow on 1 Jul 2013
Thanks, reading some of those other examples shows that using dynamic variables is a much better idea so i'll go forward with that method.
Jan
Jan on 1 Jul 2013
Sorry, I haven't seen Matt J's answer when I typed mine. This is confusing because I hit the reload button directly before answering.
While "dynamic variables" are deprecated due to the explained reasons, "dynamic fieldnames" are efficient and clean.

Sign in to comment.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!