How do I use TeX/LaTeX formatting for custom data tips in MATLAB? - matlab

I'm trying to annotate a polar plot with data tips labelled with 'R:...,Theta:...' where theta is actually the Greek symbol, rather than the word spelled out. I'm familiar with string formatting using '\theta' resulting in the symbol, but it doesn't work in this case. Is there a way to apply the LaTeX interpreter to data tips? Here's what I have so far:
f1=figure;
t=pi/4;
r=1;
polar(t,r,'.');
dcm_obj = datacursormode(f1);
set(dcm_obj,'UpdateFcn',#polarlabel)
info_struct = getCursorInfo(dcm_obj);
datacursormode on
where polarlabel is defined as follows:
function txt = polarlabel(empt,event_obj)
pos = get(event_obj,'Position');
x=pos(1);
y=pos(2);
[th,r]=cart2pol(x,y);
txt = {['R: ',num2str(r)],...
['\Theta: ',num2str(th*180/pi)]};

Update: This solution is primarily applicable to versions R2014a and older, since it appears to fail for newer versions, specifically R2014b and newer using the new handle graphics system. For newer versions using the new handle graphics system, a solution can be found here.
For some odd reason, the data cursor tool in MATLAB forcibly sets the data tip text to be displayed literally instead of with TeX/LaTeX interpreting (even if the default MATLAB settings say to do so). There also appears to be no way of directly setting text properties via the data cursor mode object properties.
However, I've figured out one workaround. If you add the following to the end of your polarlabel function, the text should display properly:
set(0,'ShowHiddenHandles','on'); % Show hidden handles
hText = findobj('Type','text','Tag','DataTipMarker'); % Find the data tip text
set(0,'ShowHiddenHandles','off'); % Hide handles again
set(hText,'Interpreter','tex'); % Change the interpreter
Explanation
Every graphics object created in the figure has to have a handle. Objects sometimes have their 'HandleVisibility' property set to 'off', so their handles won't show up in the list of child objects for their parent object, thus making them harder to find. One way around this is to set the 'ShowHiddenHandles' property of the root object to 'on'. This will then allow you to use findobj to find the handles of graphics objects with certain properties. (Note: You could also use findall and not worry about the 'ShowHiddenHandles' setting)
Turning on data cursor mode and clicking the plot creates an hggroup object, one child of which is the text object for the text that is displayed. The above code finds this text object and changes the 'Interpreter' property to 'tex' so that the theta symbol is correctly displayed.
Technically, the above code only has to be called once, not every time polarlabel is called. However, the text object doesn't exist until the first time you click on the plot to bring up the data tip (i.e. the first time polarlabel gets called), so the code has to go in the UpdateFcn for the data cursor mode object so that the first data tip displayed has the right text formatting.

Related

Matlab Get Handle for Layout

As the title states, I need to get a handle for my Matlab application. My class is derived from matlab.apps.AppBase and is app.UIFigure (if that matter, I'm still learning Matlab). My main goal is to change the mouse cursor to watch after a button is clicked and data is processed in the background.
I have tried:
set(gcf,'Pointer','watch')
But gcf is just empty, so it creates a new figure. I have also gotten all of the figures, using:
figs = findall(groot,'Type','Figure')
Which finds all of the figures I am using. I believe that I need to get the overall application figure and find the handle, but I am unsure how to do that.
There is no pointer property for uifigure; otherwise, you would be able to use app.UIFigure.Pointer = 'watch' as suggested by #CrisLuengo.
However, specially for uifigure MATLAB provides a nice looking and powerful progress bar uiprogressdlg. You can make it indeterminate with uiprogressdlg.Indeterminate = on;. I find this working pleasingly well.
Here is an example:
f=uifigure;
progressdlg=uiprogressdlg(f,'Title','Progress','Message', 'Doing something please wait', 'Indeterminate','on');
pause(10); % Run your algorithm.
% Delete the progress bar after work done.
progressdlg.delete();

Why is MATLAB's legend function so slow, and how to optimize?

Problem
In a GUI I've written I've realized that the largest bottleneck in my code performance is creating/updating the legend.
Currently I delete and recreate the legend at each update of the GUI as the user needs to be able to adjust what is in the legend. I'm currently toggling what is in the legend by adjusting the setting of LINEHANDLE.Annotation.LegendInformation.IconDisplayStyle and updating the legend using legend('off');legend('show');
Testing
The following code snippet shows that the call of legend mostly is limited by the call to legend>make_legend and is fairly independent of the legend content.
close all
n=50; % number of plot lines
S=rand(n); % data
legs=cellstr(char(26*rand(n,10)+97)); % legend entries
profile on %start profiler
plot(S)
legend(legs{:})
profile viewer % view call stats
Question
Is there a better way of updating legend content without deleting it and therefore forcing it to re-call make_legend at recreation?
Furthermore I wonder if it is known why legend in general is so slow and has such odd behavior.
Purpose
I'm adding some information here to avoid the XY Problem.
A minimal example of what I'm trying to do is:
I'm building a GUI which plots four lines, let's call them data1, data2, linear model 1, and linear model 2. The data lines are independent in both color and content, while the linear models both have the same appearance and are connected to respective data line.
I want there to be a legend which only has three entries: data1, data2, and linear model. So far, no problem.
I also want there to be three toggle-buttons which toggle the visibility of the four lines on the axes and legend. The buttons are:
data1, which toggles the visibility of both the data1, and linear model 1 data lines.
data2, which toggles the visibility of both the data2, and linear model 2 data lines.
linear model, which toggles the visibility of the linear model 1, and linear model 2 data lines.
Attempted Solutions
My first approach was to first only pass three handles to legend and then have the button callbacks adjust the visibility property of the line objects according to above.
This creates the issue that when disabling the first data line and respective linear model the legend entry for linear model also blanks out as it is connected to that specific line object, even though the other is still visible.
My current working approach instead manually sets the DisplayNameproperty of all lines and then the button callbacks adjust each lines Annotation.LegendInformation.IconDisplayStyle property. According to the documentation the user then needs to call legend to force an update.
But this is not implemented, looking at the code of legend.m it is clear that this option only returns the current legend object without any other manipulation. Therefore I'm forced to call legend('off');legend('show'); which triggers a (slow) creation of a new legend object.
This currently works but using profile I can see that the legend creation is half my computation time and has a fairly large effect on user experience when using the GUI on a slower laptop. I've already ensured that my code runs legend('off');legend('show'); only if it really has to.
The question is if any user here is able to call the unreadable, yet accessible class methods of matlab.graphics.illustration.Legend to trigger an update of an existing object without forcing it to delete and recreate. Thereby doing what the MATHWORKS documentation claims to be implemented (although it is not) in legend.
Alternatively I'm open to finding a different way of changing which line objects the current legend is tracking efficiently.
You can try to change the properties of the legend object directly. Look at http://www.mathworks.com/help/matlab/ref/legend-properties.html for a list of properties. The legend object can be accessed by:
% Assign the output of legend to a variable. Do this only once at creation.
l = legend(<some arguments>);
% Example: change the location of the legend to 'north'
l.Location = 'north';
I think this is what you asked for, but I'm not sure about any efficiency gains.

how to save figure of gui plot which will run on a computer that does not have matlab

I have made a Gui program that I compile to EXE application which lots csv file into graph data. I buit a save button but I do not know how save figure with different name each time cause (savefig anduisave both uses matlab program). I am posting my code below if anyoff you guys figure out how to save gui figue into image or anything that does require matlab to open. Last function is the callback function for save button.
function ma_Callback(hObject, eventdata, handles)
% i tried uisave but not possible to run computer without matlab cause mcr
% does not run uisave
% i tried copyopbj but since i did not put a name on my figure it did not
% work
%savefig
If you are trying to save a kind of image from your figure, then the best option which supports many aspects, is using print function.
I have already done this in a compiled app and it works perfect. Using print function you can set different file type(vector formats like *.svg are also supported), resolution(dpi), and so many others.
Although you can use print function directly on the figure, but I found that the best way (More Customization like removing or adding some objects and changing many options) is to follow this steps:
Create another figure with Visible='on' but a position that is out of screen with the same width and height of Main Figure.
normalized position = [-1, -1, ?, ?]. (Create this figure in start up and don't destroy it until your app exits, let call it Print Figure).
Copy your figure content (or the parts you are interested in) using copyobj to that figure (you may need to set Parent property of some key objects like panels to this new figure). They would look exactly as they look in the main figure, because they have the same properties. you can add or remove some objects in this step.
Change aspect ratio of "Print Figure" for a better output.
Print this figure with all options (file format, dpi, ...) you need. in my own GUI i allowed the user to change this settings with an input dialog.
In my app i used functions like winopen to show the output, and output directory to the user, when the print task was done. Print process takes some time, specially if dpi is huge, so it is also a good idea to inactivate buttons and show wait cursor.
Update:
a simple usage would be:
print(MainFigure, 'myFileName', '-dpng', '-r300')

Get selected UIControl in a GUI

How is it possible to find out which control in a given MATLAB GUI is currently selected by the user?
For example I want to find out which edit box in the GUI is currently focused since I want to exploit the figures WindowScrollWheelFcn to allow increasing/decreasing numeric values by scrolling up/down while the relevant input is selected.
Let f be a handle to the GUI figure. Then
h = get(f, 'CurrentObject')
returns a handle h to that figure's current object, which is the one most recently selected in that figure (see the documentation of figure properties for more information).
(Note that gco returns the current object in the current figure. This is not what you want, because the user may have clicked an object in another figure).

How to edit property of figure saved in .fig file without displaying it

I want to edit a certain property of MATLAB figures saved as .fig (MATLAB's default format) files.
I create a lot of graphics-intensive figures in a script, so I choose not to display them by making the default figure invisible with set(0,'DefaultFigureVisible','off'). This sets the 'Visible' property of any new figure to 'off'. This way I can create, edit, save, etc., figures without the need to draw them, which can be taxing on CPU, GPU and their memories. I save the figures as .fig files using the saveas(handle,'filename.fig') command. This also saves the 'Visible' property, which is a problem when I do want to open the figure (e.g. by double-clicking the file in my Windows Explorer). It loads the figure, but it doesn't display it because its 'Visible' property is set to 'off'.
I want all .fig files to be saved with the property set to 'on', but how can I achieve this without displaying (= taxing) the figures? The moment I use set(handle,'Visible','on'), the figure is drawn.
So basically, I want to edit the file on a lower level than when it's loaded as a figure in MATLAB.
I think it could be done as follows, but I do not know exactly how to achieve it. One can load the .fig's data as if it were a .mat file using s=load('filename.fig','-mat');. This loads a structure s containing some fields that contain all the figure's data, properties, etc. Now, the figure handle must be found in this unkown structure and the 'Visible' property that goes along with the handle edited.
Can this be done without the figure being drawn?
I tried, but haven't succeeded, using fopen, fread and their friends.
Does anybody know how to do what I want to do?
I base my solution on the thread from the url posted by user4506754: http://www.mathworks.com/matlabcentral/newsreader/view_thread/306249
There, Jesse Hopkins posts (post 15) that you can edit a property 'ResizeFcn' to execute a function when MATLAB creates a figure. This doesn't work on my MATLAB installation, but lead me to look into the different functions you can attach to a figure in its properties. This page documents all figure properties: http://mathworks.com/help/matlab/ref/figure-properties.html. There I found the 'CreateFcn' property. Its description contains:
This property specifies a callback function to execute when MATLAB creates the figure. MATLAB initializes all figure property values before executing the CreateFcn callback.
It means that the figure is loaded with its properties, including the 'Visible' property being 'off' and then 'CreateFcn' is called.
Setting 'CreateFcn' to make the figure visible then solves my problem.
set(gcf,'CreateFcn','set(gcf,''Visible'',''on'')')
An example:
ezplot(#sin) % draw a simple figure containing a sine wave, title, etc.
set(gcf,'Visible','off','CreateFcn','set(gcf,''Visible'',''on'')' % this disables the figure and set the 'CreateFcn' property simultaneously
saveas(gcf,'sin.fig') % save the figure in the current folder as a .fig file
close % closes current figure
Now go to the current folder in your Explorer and double-click the sin.fig file. It makes MATLAB load it and, poof, the figure is drawn.
Solution found.
This doesn't edit the .fig file, as I originally asked (as a solution), but it is an alternative solution to the original problem. Now I can create and save figures without them being visible, but draw the figures the moment they're loaded by MATLAB.