2

I have a nested function which calls a script basicially containing some definitions of constants and strings. I need to pass these variables to the base workspace. I know I could define them as global which is supposed to be not the best solution, is it?

The conventional way, using the output arguments of the function seems to be too complicated in my case. (It's actually just a one time call, so I don't want to blow up my code) So I thought about using assignin and who but neither it does seem to work for cell arrays nor for comma separated lists. Probably I'm just missing some syntax refinements.

function myFunction()

myScriptWithDefinitions;

% who returns a cell array with all variables from my script
temp = who;
% now I try to assign these variables to my base workspace
% these are my attempts, none of them working
assignin('base',who);
assignin('base',temp{:});
assignin('base',{temp{:}});

...
end

I'm aware that I acually need to pass both, a list of names and a list of values. any further ideas?


Edit: something like

assignin('base',{'A','B'},{2,5})
% or 
assignin('base',{'A',2},{'B',5})

does not work, so I guess assignin in general is not an option.

2
  • just for your information: the function's name is assignin and there has to be a third parameter: assignin(ws, 'var', val); but still I couldnt find a solution for the question... Commented Oct 21, 2013 at 10:12
  • yes thanks, but it was just a type here on SO not in my code. Commented Oct 21, 2013 at 10:18

1 Answer 1

2

with assignin you can only assign-in 1 variable at once.

With "who" you get a cell-array of strings, that contains the names of the variables. Now if you have this list:

myVarList=who;

you can loop over and assign the variables to the workspace:

myVarList=who;

for indVar = 1:length(myVarList)
    assignin('base',myVarList{indVar},eval(myVarList{indVar}))
end

Note: this is an eval-solution... if someone knows a quick replacement for that, please let me know :)

Sign up to request clarification or add additional context in comments.

1 Comment

I was just about to implement this ;) It's not very elegant, but working!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.