フィルターのクリア

Load a variable in workspace from a Function

31 ビュー (過去 30 日間)
Chetan
Chetan 2011 年 6 月 5 日
How to load a variable (defined in a sub-function) into the workspace?

採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 6 月 5 日
You need to clarify your question. Do you mean Matlab base workspace? You could declare the variable as global. However, many people will strongly against it.
help global
You could use return argument.
function [y1,y2]=MyFun(x1,x2)
y1=x1*x2;
y2=x1+x2;
when you call [z1,z2]=MyFun(1.1,2.2), you get the variable y1,y2 (defined in MyFun()).
  3 件のコメント
Jan
Jan 2011 年 6 月 6 日
Variables can be STRUCTs, CELLs or other types. The GLOBAL variable can have any type.
There are a lot of good reasons *not* to use GLOBALs or ASSIGNIN. Both reduce the readability and maintainability of the code drastically. And because most programmer spend more time with creating and debugging than with running a code, a clean programing technique is strongly recommended.
Fangjun Jiang
Fangjun Jiang 2011 年 6 月 6 日
@Chetan, I think your follow up questions are answered. The best approach really depends on your programming needs. If you described your original question more and provided an example, the answers would be more direct and right on target. Sounds like Paulo Silva read your mind. You should have accepted his answer.

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

その他の回答 (1 件)

Paulo Silva
Paulo Silva 2011 年 6 月 5 日
assignin('base', 'VarNameYouWishAtWorkspace', VarNameAtYourFunction)
  2 件のコメント
Chetan
Chetan 2011 年 6 月 6 日
Thank you for both of your answers. I used Assignin() that was really helpful. I was wondering (@Paulo: How did you come across this function?)
I have solved the problem using Assignin.
Apart from
1) returning
2) making the variable global
3) loading the variable in 'base' matlab workspace
is there any other way also?
Is global only applicable to variables or for structures too?
Paulo Silva
Paulo Silva 2011 年 6 月 6 日
We can find all kinds of weird functions inside MATLAB, I used it the first time inside a GUI, there's also the evalin function that you can use for similar purposes, it can even execute code on the workspace (good to define global variables on the workspace).
Global can be applied to any kind of variable but most people will tell you not to use global variables.

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

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by