Saving a variable from a function with a different name

1 vue (au cours des 30 derniers jours)
Ziv Kassner
Ziv Kassner le 4 Nov 2015
Modifié(e) : Stephen23 le 4 Nov 2015
How can I save a variable from a function into the workspace? example:
function new_name = A(a,b)
new_name = a+b;
end
I want that in the end, the variable 'new_name' will appear in the workspace.

Réponse acceptée

Stephen23
Stephen23 le 4 Nov 2015
Modifié(e) : Stephen23 le 4 Nov 2015
Simple: call that function with that variable name as its output argument:
var_name = A(X,Y);
will define var_name in the workspace where the function is being called. Passing arguments is the fastest, simplest and neatest way of passing variables between workspaces, and this is what MATLAB themselves recommend (see link below). Whatever you do, do not learn sloppy buggy programing by passing arguments using assignin or globals. Although beginners love using them, actually both of these methods make code slower and buggier.
The entire concept of functions is very similar to encapsulation, which is broken when you start passing variables willy-nilly in and out of their workspaces. It is a bad idea.

Plus de réponses (0)

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by