How to access input variable in base workspace?

Hi I want to write a function with one input parameter and no output parameters. How do I access the input parameter in its base worksapce in order to manipulate it?

1 Comment

Please provide the code so we can have a better idea of what your are doing.

Sign in to comment.

 Accepted Answer

You have to start with the base workspace. For example, you have par=1 in base workspace. Then you call your function Process(par).
Your function might look like:
function Process(Var)
VarName=inputname(1);
assignin('base',VarName,Var+rand);
However, this is not recommended because you are manipulate variables across boundary or scope. You can always do it this way, assume initially par=1 in base workspace
par=Process(par);
Where your Process() function looks like:
function out=Process(par)
out=par+rand;

7 Comments

Fangjun the question isn't detailed enough for such conclusions, we should always avoid such code.
@Paulo, the question seems clear to me. But I added caution and recommended using function with return argument to avoid cross variable scope.
It isn't clear at all and he wants to do more than one thing without providing code, it's one of those doit4me questions.
@Fangjun Jiang Thanks for the help. I will try this and see if I can get it to work.
@Paulo Silva I don't think my question was that unclear, but it is fair to ask for more of my code but it is a bit unfair to say "it's one of those doit4me questions". I was not aware of the function assignin and that seems to be what I was looking for.
@Fangjun Jiang looks like you knew exactly what I was trying to do.
Here is my code:
function inc( in_arg )
%INC Summary of this function goes here
% Detailed explanation goes here
a=inputname(1);
assignin('base',a,in_arg+1);
end
Im trying to increment a double from the base workspace that is sent to this function.
So I write:
r=1;
inc(r);
r
r=3
Works great!
@Stagleton, that could work. But you could also do as below if you define the output argument of your function. That is more safer and follow a good programming practice regarding variable scope.
r=1;
r=inc(r);
ok, thanks for the advice!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!