MATLAB: Saving a variable from a function with a different name
functionMATLABvariablesworkspace
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.
Best Answer
Simple: call that function with that variable name as its output argument:
var_name = A(X,Y);
will definevar_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, donot learn sloppy buggy programing by passing arguments usingassignin 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 toencapsulation, which is broken when you start passing variables willy-nilly in and out of their workspaces. It is a bad idea.
MATLAB actually hasdifferent workspaces! Themain workspace is called thebase workspace, but every function also has its own private workspace: this is done on purpose to keep the internal details of how functions work separate from each other and from the base workspace too.
If you want to see the variables in a function workspace, then you have two main ways to achieve this:
return some variables (i.e. output arguments) from a function to another workspace.
This is explained in the documentation too:"By default, the Workspace browser displays the base workspace. You also can view function workspaces if MATLAB is in debug mode. For more information, seeDebugging Process and Features..."
It isnot recommended to magically pass all variables to another workspace viaassignin,evalin or something similar. This is buggy and slow. MATLAB themselves describe thebest practices for passing variables around between workspaces.
Best Answer