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 commentaire

Paulo Silva
Paulo Silva le 11 Août 2011
Please provide the code so we can have a better idea of what your are doing.

Connectez-vous pour commenter.

 Réponse acceptée

Fangjun Jiang
Fangjun Jiang le 11 Août 2011
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 commentaires

Paulo Silva
Paulo Silva le 11 Août 2011
Fangjun the question isn't detailed enough for such conclusions, we should always avoid such code.
Fangjun Jiang
Fangjun Jiang le 11 Août 2011
@Paulo, the question seems clear to me. But I added caution and recommended using function with return argument to avoid cross variable scope.
Paulo Silva
Paulo Silva le 11 Août 2011
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.
Stagleton
Stagleton le 12 Août 2011
@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.
Stagleton
Stagleton le 12 Août 2011
@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!
Fangjun Jiang
Fangjun Jiang le 12 Août 2011
@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);
Stagleton
Stagleton le 15 Août 2011
ok, thanks for the advice!

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by