I think I have a basic understanding of scope, but I am a bit confused as to how this would work in a MATLAB GUI.
For instance, if I had a GUI that did a surf plot on an axes based on input from editBox1, I would have:
An updateAxes function that would update the axes with input from editBox1 (str2double(get(handles.editBox1, 'String'))).
An editBox1 callback that would call the updateAxes function.
Does it violate the idea of scope for updateAxes to directly use the get function? Should I be passing in the content of editBox1 as a parameter to updateAxes?
It is good to think about what you really need and not pass all data around. Still, handles is, in my opinion, something that can be passed around. You should also think that even if the handles are not passed around, you still have access to them. Figures are in essence global, since any figure (and thus figure properties as well) can be accessed through any function. By not passing handles around you can make it harder to access the figures, but cannot prevent access. If you have in mind to modify a figure, I can see no reason not to pass the handle to figure, or the handles to all objects in the figure. The second option will spare you some headache having to search the (recursive) list of Children in case you find out that you would need another handle to the same figure. As stated in a comment the GUI matlab have a simple way of handling this through the function guidata. Also, thinking about maintainability. Would it be easier to maintain code with a selected set of handles, properly named or sorted, or would you rather have to access them through a nameless set of Children?
Related
in a matlab script I have a vector which contains different instances of the same class. Now I would like to call the same function of each instance at the same time.
Is it, with tricky indexing, possible to do this WITHOUT a loop? For Example:
runner(1:100) = Human();
runner(:).run('fast'); % causes no error and no function call
In my project there is a vector with different neuronal networks (as objects). I tried to propagate all forward with one call.
Thanks for your time!
Well, there's one way if you're willing to modify your methods. What happens when you call something like runner(:).run('fast');? Rather than pass an instance of Human() to the run method 100 times it instead passes the entire vector of objects (an object array) to the method one time. Print out the object input from inside the method and see for yourself. Because nothing happens in your case, your run method must be written in such a way to ignore non-scalar objects. What you need to do is vectorize your methods. Depending on the nature of your methods, this may mean using for loops in some cases, but it will likely be the faster and more elegant option as it minimize the number of function calls.
Of course another option is to just call the run method 100 times using a for loop. If you really want "one call" then just hide the loop in a function or if you don't mind things to be a bit slower, use arrayfun which is nothing more than a function that hides a for loop:
arrayfun(#(obj)run(obj,'fast'),runner(:));
I am implementing (for class, so no built-ins!) a variant of the Hough Transform to detect circles in an image. I have a working product, and I get correct results. In other words, I'm done with the assignment! However, I'd like to take it one step further and try to improve the performance a little bit. Also, to forestall any inevitable responses, I know MATLAB isn't exactly the most performance-based language, and I know that the Hough transform isn't exactly performance-based either, but hear me out.
When generating the Hough accumulation space, I end up needing to draw a LOT of circles (approximately 75 for every edge pixel in the image; one for each search radius). I wrote a nifty function to do this, and it's already fairly optimized. However, I end up recalculating lots of circles of the same radius (expensive) at different locations (cheap).
An easy way for me to optimize this was precalculate a circle of each radius centered at zero once, and just select the proper circle and shift it into the correct position. This was easy, and it works great!
The trouble comes when trying to access this lookup table of circles.
I initially made it a persistent variable, as follows:
[x_subs, y_subs] = get_circle_indices(circ_radius, circ_x_center, circ_y_center)
persistent circle_lookup_table;
% Make sure the table's already been generated; if not, generate it.
if (isempty(circle_lookup_table))
circle_lookup_table = generate_circles(100); %upper bound circ size
end
% Get the right circle from the struct, and center it at the requested center
x_subs = circle_lookup_table(circ_radius).x_coords + circ_x_center;
y_subs = circle_lookup_table(circ_radius).y_coords + circ_y_center;
end
However, it turns out this is SLOW!
Over 200,000 function calls, MATLAB spent on average 9 microseconds each call just to establish that the persistent variable exists! (Not the isEmpty() call, but the actual variable declaration). This is according to MATLAB's built-in profiler.
This added back most of the time gained from implementing the lookup table.
I also tried implementing it as a global variable (similar time to check if the variable is declared) or passing it in as a variable (made the function call much more expensive).
So, my question is this:
How do I provide fast access inside a function to runtime-constant data?
I look forward to some suggestions.
It is NOT runtime-constant data, since your function has the ability of generating the table. So your main problem is to discard this instruction from the function. Before all the calls of this critical function, make sure that this array is generated elsewhere outside the function.
However, there is a nice trick I've read from Matlab's files, and more specifically bwmorph. For each functionality of this particuliar function which requires a LUTs, they have created a function which returns the LUT itself (the LUT is written explicitely in the file). They also add an instruction coder.inline('always') to ensure that this function will be inlined. It seems to be quite efficient!
I have some programs written in Matlab that I need to run several times for some reasons (debugging, testing with different input, etc...)
But, there are a lot's of graphs that are plotted by the programs and its various functions such that everytime I run the program, I have to wait for all the graphs to be displayed, which is very annoying and time consuming (especially when you are working with a small laptop).
After the program is executed, I close them with a close all.
So my question is:
Is there a way to disable all plots/figures/graphs in Matlab? either in the options, or by executing a certain code like disable plot and enable plot to ensure that no figures are being displayed.
I know that I can just browse the code and comment the plotting part, but I don't want to forget to uncomment.
Try some combination of the two commands:
set(gcf,'Visible','off') % turns current figure "off"
set(0,'DefaultFigureVisible','off'); % all subsequent figures "off"
The second one, if you put it near the beginning of your program, might do the trick for you. Of course, it is still creating the plots, which might be undesirable for computation time and/or RAM issues.
This is a classic reason to avoid Matlab when one can. It fosters bad programming design. To solve this problem correctly, you should create something that lets you "flip a switch" at the highest level of your program and control whether plots show or do not show. Perhaps it even has gradations of the show/don't show option so you can select different types of plots that do/do not show depending on what diagnostics you are running.
Ideally, you'd want this "flip a switch" creation to be a class that has access to visibility and plot functions of other objects. But because interactive object-orientation is so cumbersome in Matlab, it's often not worth the effort to develop such a solution, and most people don't think about this design aspect from the outset of their project.
Matlab would encourage someone to solve this by making flag variables like "isPlotVisible" or something, and creating functions that always accept such flags. I agree this is a bad design.
You could run matlab from the command line with:
matlab -nojvm
but then you don't get the GUI at all. Alternatively, you could write a file 'plot.m':
function h = plot(varargin)
h = [];
end
which doesn't do anything. If this is in the working directory (or somewhere else near the top of the path), then plot will call your function instead of the 'real' plot. You'd need to do the same from any other graphing functions you call.
The closest way I know of 'turning off plotting' would be a folder of such functions that you can add to the path to disable plotting, and remove to enable.
The previous methods are fine, but an easy and good habit to take is to use a "on/off parameter". So basically, at the beginning of your code, you can add something like:
DisplayFigure = 1; %1 = display, 0 = no display
After that, add "if DisplayFigure == 1 ... end" for all your plotting related commands, where the commands should be inside the if statement (the ... above). Hence you won't even compute the plots, which will save you a lot of time and memory. You just have to change the value of the variable "DisplayFigure" to plot or not the figures.
Does someone know a way how to update/draw subsystem's input or output results in runtime? In this sense, one could do a Scope block, which updates itself during the simulation, so one could see the results already by looking at the block.
Of course, my intention is not making a scope block but make some custom drawings based on results inside the subsystem in runtime.
This would mean either to:
be able to access a variable with results in plot command of masked subsystem and making sure that Simulink calls refresh everytime the variable changes
change MaskDisplay from outside, for example by inputting absolute values in plot command and signaling to Simulink that it needs to refresh that Subsystem's drawing
One way of to use a MATLAB Function block and declare plot, for example, as an extrinsic:
coder.extrinsic('plot');
You can then use plot in the MATLAB Function. You can also do this for a custom MATLAB file:
coder.extrinsic('my_custom_draw_function');
Somewhat more complicated can be to use m-file s-function.
MATLAB is a pass by value language. I have a recursive function that processes pixel's neighbors. It is very expensive to make the copy of the image (in my case two images) each time the function is called.
I used global variables to solve the problem. Is there any other way to make a recursive function modify an array?
You have three options here, but maybe you don't need any of them, since Matlab used 'copy-on-write', i.e. variables are only copied if you modify them.
As #gnovice mentions, you can use a nested function. Variables used inside the nested function are shared between the nested function and the enclosing function. Nested functions are somewhat tricky to debug, and a bit more complicated to write/understand.
You can store your images as properties of a handle object, which is passed by reference.
You can write code differently in order to not use a recursive function, since Matlab isn't the best language for using those. If you have access to the image processing toolbox, you may be able to use functions like blockproc, or im2col to rewrite the function.
Finally, if you want to stay with your current scheme, I strongly suggest using persistent variables instead of globals.
MATLAB is not always pass-by-value, newer versions of MATLAB do pass-by-reference under some circumstances, see in-place operations and a more general discussion about MATLAB memory management in this SO post.
Without tail-call optimization it is inefficient to use recursion and MATLAB does not have it as far I know, but every recursion can be transformed into a loop.
If you make your recursive function a nested function within another function where the image data is stored, then the recursive function can modify the image data without needing to have it passed to it.
This is a common misconception. Although the sytanx of MATLAB is pass by value, it does not actually pass by value as in C. The interpreter is smart enough to only make copies when necessary. So you should just go ahead and pass by value and see if you run into memory problems.
As other posters have noted, you should try to avoid recursion in MATLAB anyway.