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 件のコメント

Paulo Silva
Paulo Silva 2011 年 8 月 11 日
Please provide the code so we can have a better idea of what your are doing.

サインインしてコメントする。

 採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 8 月 11 日

0 投票

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 件のコメント

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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Programming についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by