Showing posts with label MATLAB. Show all posts
Showing posts with label MATLAB. Show all posts

Saturday, May 3, 2014

MATLAB MySQL query datetime column type

When you do a SELECT * in MySQL query from MATLAB, you would expect all the entries in the table to be returned.

Apparently, there are cases where it will not return everything. (Matlab R2013a, MySQL 5.5.32)

It seems that if you have '0000-00-00 00:00:00' in the datetime field of a row, which is the zero value of the datetime type, the row will not be returned even if you do the select all query.

However, if you are querying other columns (besides the datatime column), the row that has the zero value datetime will be returned.



Saturday, February 1, 2014

Multi-'screen' MATLAB GUI

Once again, I had little time cleaning up the post so read at your own risk. :-) 

Why bother?


First and foremost, the multi-screen GUI I am talking about is much like a Single Page Application (SPA) in the context of web application. Everything you see in the GUI can change entirely as you 'navigate' from "screen" to "screen". An example would be an application that has various stages to it, as the user goes from stage to stage, only the relevant information/controls will show on the GUI. Of course, you can always just slap everything on the GUI without considering splitting them into "screens", but you only have so much space on the GUI and every bit of information that shouldn't be there is wasting the UI space.

<begin digression>
Also, one can also implement the application using multiple GUIs instead of multiple screens. Such approach is more appropriate in the case where the different GUIs have to be shown at the same time, but there are distinct features about each GUI so it doesn’t really make sense to put them all in the same GUI, also, reusability is another issue. But that’s a different topic altogether.
<end digression>

Enough background. Below is how.

First of all, there is no such feature (multiple-screen GUI) in Matlab, but there is a little trick we can use to make it appear so, and that is with the use of 'uipanel'.

The concept is fairly simple, assuming you have already got a design in mind, i.e., you are clear about what uicontrols go into to what uipanel, all you need to do is have them populated in the right panels, subsequently, we show and hide the panels as we see fit. Note that the panels should have been resized at this point so they overlap completely, and at any given time, only one panel should be shown (Visible = 'on'), while others are hidden (isVisible = 'off'). (I don't understand why 'on'/'off' are used instead of true/false or 1/0.)

Now, I would strongly recommended creating everything programmatically instead of relying on Matlab’s GUIDE, as the panel will need to be resized, moved around, which is impossible to do in GUIDE. You also need to pay special attention to the unit setting for all the uicontrols when you are doing this, if there is any mis-matches or invalid values, then the uicontrols may not show up, or when you resize the GUI, the uicontrols in a panel may all go crazy.
Below is the link to a fairly simple demo that shows the multi-screen in action of the application. Three buttons to show one of the three panels (much like the tab effect if you just position them in a better way).
https://github.com/weishang/matlab-multiScreen

What else?


The trick described in this post is using overlapping panels as screens and show/hide the panels as you desired. Here’s what else you can do with this trick.
  • A demo application which goes from one screen to the next, much like a slide show. With the help of the timer object (may find this post useful). 
  • A GUI with the ‘tab’ effect 
  • A fully blown single page application 
  • ...

Saturday, August 31, 2013

MATLAB GUI and Timer Object

I shouldn't really started this post at all since I have little time to 'beautify' the post, but what's described in this post can be very useful for someone that needs to have the GUI update itself at a fixed time interval, say, plotting the latest forecast data. Note that it doesn't have to be a fixed timer interval, in fact if you put enough thought into this, the schedule for the updates can be very flexible (by using database, etc).

Be warned though, the quality of the post is lacking, but I will make sure the sample application is running as expected so all you need to do is to expand on it and plug in all the pieces you need/have.

If you are not familiar with MATLAB GUI, you should read up on it (and unfortunately this post is probably not for you). If you are fairly familiar with MATLAB GUI, but haven't used  the timer object much. Here is the documentation, it is best if you try out a few examples that uses timer object without the GUI, just to get a feel for it.

Now, without further ado, below is a walk through of creating a MATLAB GUI-based digital clock (from scratch).

1. Type GUIDE in matlab, and choose to create a blank gui.

2. Create a static text on the GUI, make it and its fontsize big, and tag it as lbl_timeNow

3. Save the GUI (with the name, say, myClock), and open up its m-file.

4. In the OpeningFcn (prefixed with whatever name), insert the following code

timer_obj = timer(...
    'StartFcn',         @user_timer_start, ...              % start function
    'TimerFcn',         {@user_timer_update, hObject}, ...  % timer function, has to specific the handle to the GUI,
    'StopFcn',          @user_timer_stop, ...               % stop function
    'ErrorFcn',         @user_timer_err, ...                % error function
    'ExecutionMode',    'fixedRate', ...                    %
    'Period',           0.1, ...                           % updates every xx seconds
    'TasksToExecute',   inf, ...
    'BusyMode',         'drop');


start(timer_obj);        % start the timer object

setappdata(hObject, 'timer_obj', timer_obj');  % save the timer object as app data

Effectively, we just created and started a timer whose TimerFcn gets executed every 0.1 second. And the timer is saved as the app data so when we try to close the GUI, we can easily get our hands on the timer and get rid of it at the same time. 

5. Implement the user_timer_update function (which is set as the TimerFcn of the timer). Insert the following function to the m file. Notice how it has three input parameters, the last of which was past in in step 5 with '{@user_timer_update, hObject},'.

function user_timer_update(src,evt, fig_handle)

handles = guihandles(
fig_handle);

set(handles.lbl_timeNow, 'string', datestr(now, 'yyyy-mm-dd HH:MM:SS'));


6. Put in the other timer functions, StartFcn, StopFcn, ErrorFcn into the m file. They are just dump text printer for now. 

function user_timer_start(src, evt)
disp('Timer started!');

function user_timer_stop(src, evt)
disp('Timer stop');

function user_timer_err(src, evt)
disp('Timer error');


7.  We are almost done, just need to make sure the timer is removed when we close the GUI. So go to the GUIDE editor, and select 'CloseRequestFcn' property of the figure, it should populate the function in the m file for you. Now, before delete(hObject), put in

stop(getappdata(hObject, 'timer_obj')); % stops the timer 
delete(getappdata(hObject, 'timer_obj'));  % delete the timer object 

8. Now, here is a list of things that you may want to do: 

  • make the gui look pretty 
  • properly implement the other timer functions, StartFcn, StopFcn, etc. 


Here is what it looks like and here are .fig and .m files. 



Well. That's all for now. Good luck. 

Saturday, July 27, 2013

Connecting to (local) MySQL database in MATLAB

If you try to connect to a local MySQL database based on the Matlab documentation on the database function (see connection example here), you are likely to get the 'Unable to find JDBC driver' error. 

To fix the error, first download the JDBC driver from MySQL website. 


Once download, unzip and find the mysql-connector-java-5.0.8-bin.jar (or more current version) file and move it to Matlab's java path ($matlabroot\java\jar\). 

Next, type prefdir in MATLAB and find your preferences folder, once in that folder, create a text file called javaclasspath.txt, and place the $matlabroot\java\jar\name_of_the_jar_file in and save the file, restart Matlab.

Now if you type javalclasspath, you should see the jar file appear at the bottom of the static path.

Finally, to test out if everything works as expected, run 

conn = database('mysql', 'root', 'DB_password', 'com.mysql.jdbc.Driver',  'jdbc:mysql://localhost/');

conn

tables(conn)


close(conn);

* May need to adjust database name, user account, password, driver name, and url of the database. 


Monday, May 14, 2012

Drawing path taken in MATLAB

In this entry, I am showing a way of plotting path in MATLAB, which is often seen in pattern recognition and statistical modelling technique, for example, the Needleman-Wunsch algorithm and the Hidden Markov Models. Provided that the length of the output sequence is relatively short, and there are limit number of states, it may be beneficial to be able to visualize the path.

Below is an example based on the Needleman-Wunsch algorithm for sequence alignment. Note that all the cells are shown in the plot as text objects, and the available path is shown as thin lines while the optimal path obtained from the back tracking process is shown as thicker lines.
Note that even though the lines appear as broken segments in the plot, they are not drawn as such. It is rather difficult to figure out the starting and ending points of the line to produce a consistent and nice-looking plot. Instead, the lines are drawn between the centers of the text boxes. It looks like segments because there are solid white circles drawn on top of the lines, effectively, we are covering parts of the lines using white circles. Note that you can use rectangle(), which is a MATLAB function, to draw the circles, and you can set their facecolor and edgecolor to white, which will give the circles with solid white background.

The trick is to know that all the graphic objects are being placed on differently layers (or stacks). Usually, the objects that are added to the figure last will always appear on the top of everything else. So, depending on the order of how you draw things, the plot may appear different if there is any overlap between the objects.

To generate the above plot, plot the lines first, and then the white circle, and finally the text boxes. Note that in the case where the lines have to be drawn last, you can always use to uistack function to send the lines back to the bottom layer of the figure.

This rather messy m-file contains the code that produces the above plot.

Saturday, April 21, 2012

Detecting the type of mouse click

There are many ways for a user to interact with application using a mouse, there are normal click (single left click) that often selects the object, single right click that often opens up a context menu, and double-left click that often opens up the object. The ability to detect the type of the mouse click will come in handy when you are developing a truly interactive GUI. Fortunately, such information can be easily obtained by extracting the information stored in the SelectionType property of the GUI, which is a figure object.

1. Create a blank GUI and save the files.

2. Create a function to be attached to the WindowButtonDownFcn property of the GUI.


function winButtonDownFcn(hObject, eventData) 
m_type = get(hObject, 'selectionType');
if strcmp(m_type, 'normal')
    fprintf('left mouse click\n');
elseif strcmp(m_type, 'alt')
    fprintf('right mouse click\n'); 
elseif strcmp(m_type, 'open')
    fprintf('double-click\n');
end

3. In the opening function of the GUI, attach the function to the WindowButtonDownFcn property of the GUI.

set(hObject, 'windowButtonDownFcn', @winButtonDownFcn);

4. Running the GUI and try out different type of mouse clicks, the corresponding detection should be printed in the command window.

Note that there are other mouse clicks and/or key pressed may result in the same values in the selectionType property, for example, Control+left click will show up as a right click. If you would like to implement the more complicated mouse clicks (with key pressed), be sure to check the table in the documentation.

Example can be download here.

Tuesday, January 24, 2012

MATLAB GUI: inserting background image to push/toggle button

This is a brief tutorial on how to insert background image to push button and toggle button in MATLAB GUI. The idea is simple, read in the background image as a matrix, and then assign the matrix to CData property to the buttons.

1. Create a new GUI in MATLAB using GUIDE, and save the file.
2. Add uicontrols push button (or toggle button), rename their tag as pb (or tb).
3. In the OpeningFcn in the corresponding m-file, copy and paste the following code:

bg_image = imread('button.jpg');
set(handles.pb_with_bg, 'CData', bg_image);

Note, you may want to set pixel as the figure's unit so that you can easily figure out the size of the button that will show you the entire background image. In other words, the size of the button and the size of the background image should match.  


Video


Files
Source files can be download here.

Saturday, January 21, 2012

MATLAB GUI: Tracking mouse locations


In the first part of the series, we will create a simple GUI that will show the current position of the mouse on the GUI.

Step-by-step guide:
  1. Create new GUI using MATLAB GUIDE, save file as gui_mouse
  2. Create two static text fields and configure them as fellow
    1. rename tags to lbl_x and lbl_y
    2. set strings to 'x loc:' and 'y loc:'
    3. set FontSize to 18, and resize components 
  3. Configure figure property (double-click on figure)
    1. rename tag to fig_mouse
    2. change unit to pixels
    3. click on callback for WindowButtonMotionFcn and insert the following code
    pos = get(hObject, 'currentpoint'); % get mouse location on figure
    x = pos(1); y = pos(2); % assign locations to x and y
    set(handles.lbl_x, 'string', ['x loc:' num2str(x)]); % update text for x loc
    set(handles.lbl_y, 'string', ['y loc:' num2str(y)]); % update text for y loc 


  4. Save all files and run the GUI or M-file.
Note: anytime the mouse is moved over the GUI, it will trigger the WindowButtonMotionFcn on the figure, which will then update the labels with the current location of the mouse pointer on the figure. 

Video:




Files:

Download source files here. 

Friday, January 20, 2012

MATLAB GUI tutorial planned


I am planning to create a tutorial series on how to incorporate mouse movements and actions into MATLAB GUI. Traditionally, the GUIs are designed to accept user input via a variety of uicontrols (or components). While having the components are sufficient in most applications, there are still cases where the user experience may be drastically enhanced by utilizing mouse movements and actions.

The end-product of the series is a GUI that allows user dragging and dropping an object in the GUI. The series will contain a number of tutorials, each dealing with a specific subject (or sub-problem). Each tutorial will be built on the earlier tutorials, either provides a different functionality or a more advance usage of the same functionality (or both).

The series of tutorials may cover the following topics (subject to change)

Thursday, January 19, 2012

SVL Suite V1.0.0 available for download

My submission of SVL Suite to MATLAB Central File Exchange was rejected. The reason for the rejection is because my submission contains p-files. Having the p-files, which hides the source code, kind of defeats the purpose of File Exchange, which is to allow users to learn from each other by looking at the source code. It is fair, but I wish they had spelled it out in their Guidelines for New Submissions.

In any case, I believe SVL suite is a very useful application/learning tool and I am determined to at least try to give it a bit of exposure on the Internet. And therefore, I updated the project website I created for the SVL Suite (in 2010), and package up the first release for download. I also submitted the link of the project website to the Link Exchange on MATLAB Central. Let's see where it takes us. 




Thursday, January 12, 2012

Signals Virtual Lab (SVL) Suite

Signals Virtual Lab (SVL) Suite is a collection of MATLAB GUIs that was developed for the introductory Signals course at the University of New Brunswick. The goal of the suite is to provide students with a good learning experience while maintaining the look-and-feel of the equipment used in the lab.

The video below shows a brief and basic demo of the Signal Virtual Lab Suite. It involves connecting the function generator to the oscilloscope, changing parameters of the input signal, changing the display parameters on the oscilloscope, and finally, computing and displaying the spectrum of the input signal. Cursors are also used in the demo as to measure magnitudes and frequencies of data points on the spectrum.

Tuesday, January 10, 2012

Auto- and Cross-correlation demo in MATLAB

Purpose of the GUI is to help readers visualize the auto- and cross-correlation of discrete time signals.

A screenshot of the cross-correlation demo using MATLAB GUI

How to use:
  1. Download MATLAB files from here.
  2. In MATLAB, navigate to the folder where the files are stored 
  3. Type gui_xcorr and hit Enter. 

Acceptable formats as input discrete-time signals:
  • An array, such as [3, 2, 1, 5] or cos(2*pi*0.02*(0:99))]
  • A 2-row matrix with the top row storing sample indices and the bottom row storing sample data, such as [0:3; 3 2 1 5] or [0:99; cos(2*pi*0.02*(0:99))]