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 Kommentar

Paulo Silva
Paulo Silva am 11 Aug. 2011
Please provide the code so we can have a better idea of what your are doing.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Fangjun Jiang
Fangjun Jiang am 11 Aug. 2011

0 Stimmen

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 Kommentare

Paulo Silva
Paulo Silva am 11 Aug. 2011
Fangjun the question isn't detailed enough for such conclusions, we should always avoid such code.
Fangjun Jiang
Fangjun Jiang am 11 Aug. 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 am 11 Aug. 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 am 12 Aug. 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 am 12 Aug. 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 am 12 Aug. 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 am 15 Aug. 2011
ok, thanks for the advice!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by