How to set global variables for different GUIs in Matlab? - matlab

I want to do something like this: a program where at the beginning some data is initialized. Then I open other GUIs where I show some graphics from these data.
Is there any possible way to set some global variables for different GUIs? If not, how could I do it?

As long as you pass the handle of the first GUI to the second, you can access all the properties of GUI#1 from GUI#2 (and vice versa, since the GUI creation method returns the handle to GUI#2).
Alternatively, you can collect the data you want to visualize (as well as the handles of the GUIs) in a handle object, which means it is passed by reference and thus available everywhere.
Finally, you can, of course, create global variables - at the beginning of any function that would like to access these variables you have to declare them as global var1, var2, var3.

Related

Collect internal variables of nested functions in matlab

I have a project consisting of multiple nested functions.
For debugging purpose I want to save all internal variables in one way or another, in order to display figures, replay parts of code etc...
I also want to keep this as transparent as possible regarding calculation time.
My first thought was to create a global variable, and store programmatically at the end of each function the inputs and outputs inside the variable as a structure :
globalVariable.nameOfParentfunction_NameOfFunction.nameInput1 = valueInput1;
globalVariable.nameOfParentfunction_NameOfFunction.nameInput2 = valueInput2;
...
globalVariable.nameOfParentfunction_NameOfFunction.nameOutput1 = valueOutput1;
...
Is it possible to use some kind of reflection to get the name and value of inputs/outputs without necessarily parse the file where the function is written?
I found a good but maybe outdated topic about parsing
How do I collect internal signals?
The simple solution is to use save, which will save all variables in the current workspace (the function’s context) to file.
If you want to keep the values in memory, not in a file, you can use names = who to get a list of all variables defined in the current workspace, then use val = eval(names{i}) to get the value of the variable called name{i}.
I would recommend putting all of that in a separate function, which you can call from any other function to store its variables, to avoid repeating code. This function would use evalin('caller',…) to get names and values of variables in the workspace of the calling function.
Note that using eval or evalin prevents MATLAB from optimizing code using its JIT. They also are dangerous to use, since they can execute arbitrary code, however in this case you control what is being executed so that is no a concern.

Define a variable and use it in all sub-function on Matlab

Is there any way to define a variable in main function and use it in all sub-function.
I've tried to declare variables as global but it seems I should repeat it in all function again. I'm wonder what's the benefit of global variable at all!
use variable as global:
main program
global x
syms x
subfunc1
subfunc2
...
and
subfunc1
global x
and
subfunc2
global x
(maybe this format remind us to have global variable in function but it was better to cause error if we use same name of variable in function same as Matlab keywords)
I don't want to import the variable as all function argument and don't want to declare that variable in all function again and again.
any help would be appreciated.
If you really want to have access to the same variable, then there are only two ways I know of in Matlab:
nested functions(described by answer from #justthom8) and global variables. Other methods of getting data into functions exist, such as getappdata, guidata and (my personal favorite:) passing function arguments. However, these approaches make copies of variables.
Perhaps you should ask yourself why you want to avoid making copies of variables. If you are worried about performance, you should know that Matlab efficiently use variables as reference to data only, so you can safely send a variable in to a function (thereby copying the variable) without copying the actual data. its first after you modify the data inside of the function that the data is actually copied. All this is totally invisible to us, except as a possible drop in performance during alot of copying. This is called copy-on-write.
Global variables can be used to optimize Matlabs performance, by coding them in such a way as to avoid copying data, but that really requires knowing what you are doing, and it opens up for a whole lot of pitfalls, especially if your projects grow in size.
One thing you can do is define the other functions as subfunctions of the main function. Something like below
Both of the functions subFunc1 and subFunc2 should have access to data you define above it in mainFunc
function mainFunc()
variable1 = 'stuff';
variable2 = 5;
function subFunc1()
%do stuff
end
function subFunc2()
%do more stuff
end
end
Edit 1
Of course you can define global data in the mainFunc that gets used in the subfunctions, but I wouldn't recommend doing that since it can get changed in unexpected ways that you don't intend for to happen.

MATLAB best practice: reading variables from a saved workspace within a method

I have a a workspace called "parameters.mat", which contains many variables (really, constants) used by several methods throughout my simulation. The reason that I want these in one workspace is to have them in a handy place for the user to change.
I want to access these variables within class methods. I've found two ways of doing this, and I'd like to know which one is considered better (or perhaps if there's an even better way):
Load the workspace before anything else, as the base workspace, and whenever I want to use a variable from it within a method, I call evalin('base', 'variable_name') first.
Load the workspace within the method whenever I need it. This works,
but it gives me a warning when I use an undefined variable name in
the rest of the method (because MATLAB doesn't know it will be
loaded from a workspace). Is there a clean way to remove this warning?
Probably the cleanest way to do this is to use a wrapper function. Building on my comment, assuming your parameter constants are in a file parameters.mat:
function value = param(name)
s = load('parameters.mat');
value = getfield(s, name);
Now you can use a syntax like
var = param('name');
wherever you need the value of this variable. This way to do it is easily understandable to humans, and transparent to Matlab's code checker. You can also use param('name') directly in your computations, without assigning the value to a local variable.
If the parameter file contains more than just a few numbers, and loading it time after time slows down things, you can cache the data in a persistent variable:
function value = param(name)
persistent s
if isempty(s)
s = load('parameters.mat');
end
value = getfield(s, name);
Now the mat-file is read only on the first call to param(). The persistent variable s remains until the next clear all (or similar, see clear) or the end of the Matlab session. A drawback of this is that if you changed the mat-file, you have to clear all in order to make param() re-read it.
If on the other hand your mat-file does only consist of a few numbers, maybe a mat-file is not even necessary:
function value = param(name)
s.x0 = 1;
s.epsilon = 1;
s.dt = 0.01;
value = getfield(s, name);
With this approach the function param() is no longer a wrapper, but a central location where you store parameter values instead of a mat-file.

Good way to pass many variables to function?

When one has a function, which needs many specific variables when called, what is a good way, to pass them?
Should one always pass all variable explicitly? How about storing them in structs (or objects)? But somehow I think, this makes things a bit obscure, as these structs/objects have to be well defined to make sure, they have all the fields, when handed in to the function in question.
Also probably local variables are accessed most quickly, whereas adressing struct fields might be slow in a loop...
Or is it a good thing to run an external script where everything is defined global (but even in this case on has to make everything available to the function using the global keyword)
A good way to pass many variables to a function, is to use varargin. Use it together with nargin.
function varlist2(X,Y,varargin)
fprintf('Total number of inputs = %d\n',nargin);
nVarargs = length(varargin);
fprintf('Inputs in varargin(%d):\n',nVarargs)
for k = 1:nVarargs
fprintf(' %d\n', varargin{k})
end
Varargin can also be used for optional variables.. So it gives a lot of options...

Pass variable from GUI to function in MATLAB

I have a MATLAB GUI that loads to aid in visually pre-processing data. Essentially it prompts the user to adjust the data range, reduce number of data points, etc... all while providing an updated graph. Upon completion of this work, I want to be able to close out the GUI and pass variables from the GUI to another MATLAB function that does the data analysis. I have found lots of information on how to pass information from a function TO and GUI, but not the other way around.
Any help would be greatly appreciated.
Global variables can cause hard to find bugs. The best solution for your problem (where you want to pass the data directly to another function on close) might be to call the analysis function from the Figure Close Request Function. When the figure your GUI is running in is told to close, it will run the code in this function, which can call your analysis function and have access to the GUI's data.
Matlab GUIs are functions: the code exists in a .m file just like other functions. Like regular functions, they can have return values. You can get as fancy as you want messing with the varargout system, or you can simply return a value, structure, or cell array containing whatever you want. Open up the m-file and edit it to return what you want it to.
Note: If you require special processing when the figure is being closed to generate the appropriate return value, you can reimplement the closeRequestFcn as you see fit.
The easy way: you declare as global variable, where variable stores the data that you want to carry from the GUI to the main MATLAB workspace. Then, you also declare the same global variable on the command window. Hereinafter, variable to be accesible from both scopes, the GUI and the main workspace.
You could also use save or any other alternatives as csvwrite or dlmwrite to store the data into a file, but this doesn't seem to be your case.