Matlab: How to return output from a function in a set()? - matlab

I am now using Matlab GUI and have problem during accessing return values from a function which is set by set().
Situation:
I set the windowMotionFcn as below:
set(gcf,'WindowButtonMotionFcn',#test);
Function 'test' can return 2 variables (named as var1 and var2).But I dont know how to store them...
I have searched in the Internet and could not find any way.
How should I write?
Thank you for your help and kind attention.

I think that what you want to do is to return a value from the callback function. And regarding returning a value from a callback I am not sure that is possible. I found an old article from matlab newsreader. I think your problem could be similar.
However, if you have a matlab GUIDE GUI, there is a way to return a value from a gui. It is described in a matlab tutorial in matlab central: advanced-getting-an-output-from-a-guide-gui. What you must do is to modify your CloseRequestFcn and your OutputFcn.
Another way, which should work is using global variables. A global varable exist in the global workspace. That means that it can be seen and accessed by every function in matlab. Global variables are in most cases not recommended, but if no other solution exists they may be necessary. Just make sure to document them, so that the next person to take over your code knows that they are there. Also make sure to select a good name for the globals, like gblMyVar so there can be no confusion that the variable is global.

Related

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.

Simulink - How to create independent custom blocks using callback functions

I am currently coding a new library with several models in it (I am used to Matlab, but not to Simulink). I am able to create a model with block parameters, let's say parameter 'p', and a callback function (initfct) which uses this parameter to compute specific values used inside my model (let say a simple gain K=K(p)).
My problem is that my parameter 'p' and 'K' are available directly on the workspace, what I don't want to. Moreover, if I use twice or more this model in a system, the two models share always the same 'K', which also I don't want to.
So how I can make these variables 'p' and 'K' independent when I use my custom model several time, and to prevent these variables to be viewed in the workspace ?
Should I use "Reference models", but I am not familiar with this feature ... ?
Thanks for you answer,
Michael
Within a callback, gcb returns the path to the block which currently executes the callback. Having the path, you can use get_param to access the parameters.
Just for demonstation purposes, insert the following to the MoveFcn of a delay block:
set_param(gcb,'DelayLength',num2str(randi(10)))
It will randomly change the delay whenever the block is moved.
I am not sure if my answer explains everything you need. It might be that you also need a Mask. If you think this answer is incomplete, please update your question and include a small example model demonstrating your problem.
Thanks, with your help I was able to solve the problem.
To be more specific if someone else has the same problem : you need in your mask to declare also internal variables used by the callback function. Unchecked the relevant options so that they not appear as standard input parameters of your model.
My problem was also to use num2str instead of mat2str (when the gain was a matrix acting on multiple inputs).

Find indirect calls to specific built-in MATLAB function

What do I want?
I am looking for a way to detect all points in my code where a specific function is called.
Why do I want it?
Some examples:
Some output comes out sorted or randomized, and I want to know where this happens
I am considering to change/overload a function and want to know in which part of my code this could have impact
What have I tried?
I tried placing a breakpoint in the file that was called. This only works for non builtin functions which are called from short running code that always executes everything.
I tried 'find files', this way I can easily find direct calls to sort but it is not so easy to find a call to sort invoked by unique for example.
I have tried depfun, it tells me:
whether something will be called
from where non-builtin functions will be called
I thought of overloading the builtin function, but feels like a last resort for me as I am afraid to make a mess. | Edit: Also it probably won't help due to function precedence.
The question
What is the best way to track all potential (in)direct function calls from a specific function to a specific (built-in)function.
I don't exactly understand your use case, but I guess most of the information you want can be obtained using dbstack, which gives you the call-stack of all the parent functions calling a certain function. I think the easiest way is to overload built-in functions something like this (I tried to overload min):
function varargout = min(varargin)
% print info before function call
disp('Wrapped function called with inputs:')
disp(varargin)
[stack,I] = dbstack();
disp('Call stack:')
for i=1:length(stack)
fprintf('level %i: called from line %i in file %s\n', ...
i, stack(i).line, stack(i).file);
end
% call original function
[varargout{1:nargout}] = builtin('min', varargin{:});
% print info after function call
disp('Result of wrapped function:')
disp(varargout)
I tried to test this, but I could not make it work unfortunately, matlab keeps on using the original function, even after playing a lot with addpath. Not sure what I did wrong there, but I hope this gets you started ...
Built-in functions take precedence over functions in local folder or in path. There are two ways you can overload a built-in for direct calls from your own code. By putting your function in a private folder under the same directory where your other MATLAB functions are. This is easier if you are not already using private folder. You can rename your private folder once you are done investigating.
Another way is to use packages and importing them. You put all your override functions in a folder (e.g. +do_not_use). Then in the function where you suspect built-in calls are made add the line "import do_not_use.*;". This will make calls go to the functions in +do_not_use directory first. Once you are done checking you can use "clear import" to clear all imports. This is not easy to use if you have too many functions and do not know in which function you need to add import.
In addition to this, for each of the function you need to follow Bas Swinckels answer for the function body.
Function precedence order.
Those two methods does not work for indirect calls which are not from your own code. For indirect calls I can only think of one way where you create your own class based on built-in type. For example, if you work only on double precision types, you need to create your own class which inherits from double and override the methods you want to detect. Then pass this class as input to your code. Your code should work fine (assuming you are not using class(x) to decide code paths) since the new class should behave like a double data type. This option will not work if your output data is not created from your input data. See subclassing built-in types.
Did you try depfun?
The doc shows results similar to the ones you request.
doc depfun:
...
[list, builtins, classes, prob_files, prob_sym, eval_strings, called_from, java_classes] = depfun('fun') creates additional cell arrays or structure arrays containing information about any problems with the depfun search and about where the functions in list are invoked. The additional outputs are ...
Looks to me you could just filter the results for your function.
Though need to warn you - usually it takes forever to analyze code.

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.

how a function change in a loop with newtonsys command matlab

i want to change function variable at each step in a for loop in matlab.
i take these steps:
i created my mfile function
function [jfun,fun]=air(x,vt,ty,tz,p2,y0)
jfun=[(cos(tz)*cos(ty)*vt/9.81)*(1-exp(-9.81*x(2)/vt)),...
x(1)*cos(tz)*cos(ty)*exp(-9.81*x(1)/vt);
(-vt*sin(tz)*cos(ty)/9.81)*exp(-9.81*x(1)/vt),...
(x(1)*sin(tz)*cos(ty)*+vt)*exp(-9.81*x(1)/vt)];
fun=[(x(1)*cos(ty)*cos(tz)*vt/9.81)*(1-exp(-9.81*x(2)/vt))-p2;...
(vt/9.81)*(x(1)*sin(tz)*cos(ty)+vt)*(1-exp(-9.81*x(2)/vt))-vt*x(2)+y0];
end
and then i used newtonSys command:
ty=rad(-23)
tz=rad(15)
p2=1.8
vt=8.4925
y0=0.2
myfun=#(x)air(x,vt,ty,tz,p2,y0)
x=newtonSys(myfun,[15 5],0.000001,0.000001,500,1)
and matlab answer:
Error in ==> Untitled18 at 7
x=newtonSys(myfun,[15 5],0.000001,0.000001,500,1)
i guess that its because of wrong use of function handle and for my function i have to use another command or i have to use another method for solving 2nonlinear equation.
First, you haven't displayed the entire error. MATLAB should tell you what the actual error is, so unless you tell us that, we won't know what's wrong.
Secondly I don't see newtonSys in my system, or in the online MATLAB documentation. So most likely it is an external program, which most people here might not be familiar with. The closest I found from a quick Google search was this, which is an implementation of Newton's method for approximating the root of a non-linear system of n-equations. Are you using the same file? If so, if you look at the comments, it says that you need to pass the function as a string. So you'd have to pass myfun as 'myfun'.
If not, could you edit your question and add the contents of the function that you're using? Without these, it's near impossible to answer your question.