Doug’s MATLAB Video Tutorials

October 16th, 2007

MATLAB Basics: Setting a background image for a GUI

I recently got a question in my inbox asking how to set the background image for a GUI. This is done by creating an axes in the GUI and putting an image in it. Any UICONTROLs that you put on the GUI will appear over the image. See this video for the details:
Find the files here. Other videos have been gathered here: http://blogs.mathworks.com/pick/category/video/ Other MATLAB Basics posts have been gathered here: http://blogs.mathworks.com/pick/category/matlab-basics/

43 Responses to “MATLAB Basics: Setting a background image for a GUI”

  1. Craig Miller replied on :

    Nifty idea. Is there a way to do this without using imshow from the Image Processing Toolbox, with just ‘plain’ Matlab?

    Thanks,
    Craig

  2. Doug replied on :

    With a little work, IMAGE should do fine here also. It is just that IMSHOW, from the image processing toolbox, takes care of many book keeping type tasks for you so your image always looks great.

    Doug

  3. Vaibhav Bedia replied on :

    I am having some problems with the background image.Things work fine once but if i close MATLAB and start the GUI again the axes loses its TAG and hence the axes becomes invisible.I need to rename it manually everytime.Is there a way to solve this?

  4. xiaolan replied on :

    May i know how to put an image on a button? i don’t want any wordings on the button, i just want to have image on it.

    Thanks.

  5. Doug replied on :

    xiaolan,

    You can put an image in a button like this:

    a = uicontrol(’style’,'pushbutton’)
    set(a,’cdata’,rand(10,10,3))

    I set he cdata to a random RGB matrix, but you can use whatever you like.

    Doug

  6. tasha replied on :

    i really need help on my MATLAB GUI program. can anyone help me? please email me at intan_tassya@yahoo.com if you’re wiling to help me.

    i’ve create a simple GUI interface. im using MATLAB V.7.2.. but i don’t even know how to input the function . for example, total_area= area1+area2 when we press the ‘calculate’ button. can anyone show me 1 clear example on this matter, i need to complete my project within 1 week starting from today…i’ve read all your comments etc, but i couldnt understand it.. besides, im importing the jpeg image into the axes which i labelled as ‘pic1′…when i generate, the picture will be displayed, but when i click the ‘next’ button, and trying to go back to the previous interface, the image gone. i dont understand why…please somebody, i really need help on MATLAB GUI…please email me..thank you very much :(

  7. Doug replied on :

    Tasha,

    I would recommend this video:

    http://blogs.mathworks.com/pick/2008/05/13/accessing-data-from-one-widget-to-another-in-guide/

    It will show you how to get data from one uicontrol (like an editbox) and use it as input in the callback of another.

    I am sorry, but I am not too clear on your second question. Please contact support@mathworks.com with a more detailed question.

    Doug

  8. Ed Helwig replied on :

    Doug,

    I tried following your set up for putting an image into the axes and I continue to only get the X/Y plot displayed. I have even created a new fig and got the same result. Where should I begin looking for the problem? I am using version 2007b.

    Thanks in advance.

  9. dhull replied on :

    Ed,

    Please post your code for review.
    Shorter and simpler is better for us to look at.

    thanks,
    Doug

  10. mark replied on :

    Please can you tell me where you saved the ‘pout.tif’ image. I have saved my image (new.bmp) in the same folder that with the GUI file and the M-File. Below are my codes, but i didn’t get the image in the background. it only showed a numbered x and y axes. Can you help please.

    % — Executes during object creation, after setting all properties.
    function axes1_CreateFcn(hObject, eventdata, handles)
    % hObject handle to axes1 (see GCBO)
    % eventdata reserved - to be defined in a future version of MATLAB
    % handles empty - handles not created until after all CreateFcns called

    % Hint: place code in OpeningFcn to populate axes1

    axes (hObject)
    imshow(’new.bmp’)

  11. dhull replied on :

    @mark,

    Pout.tif was here:

    >> which pout.tif
    C:\Program Files\MATLAB\R2009a\toolbox\images\imdemos\pout.tif

    In the debugger, put a breakpoint right before imshow, use which as I did above to make sure the file is on your path.

    Doug

  12. vasso replied on :

    Doug,
    is there any way to set a background image for my GUI and, on that, clip another axis in order to display images?
    Generelly, can I clip on an axis another axis?
    I tried doing it the way you propose, but the images the two axes display (the background image and the image I want to display) get mixed.
    Thanks in advance for your reply!

  13. vasso replied on :

    sorry for the mixed use of axis and axes! I hope you understood what I meant!

  14. dhull replied on :

    @vasso,

    I do not understand your question. Please contact http://www.mathworks.com/support

    Doug

  15. mark replied on :

    Thanks Doug… I got it now. Many Thanks. Doug, do you have tutorials on Plotting graphs using Matlab GUI? I’ve done most of your beginner’s lessons but I can’t find one for plotting graphs

  16. dhull replied on :

    @mark,

    http://blogs.mathworks.com/videos/2009/07/10/basics-visualizing-a-function-of-two-variables/

    This is one of the many videos that cover graphics in some way. Anything specific you would like to see?

    Doug

  17. mark replied on :

    Thx for the reply Doug. The video was very informative. But I’m after tutorial on plotting graphs. Say I want to plot the values of X against y values using GUI AXES. How do I define X and Y? Give title and axes range to the plot using GUI

  18. dhull replied on :

    @mark,

    It would be easier to help if I knew what you have already tried. Please e-mail me the details and the code you have tried.

    Thanks,
    Doug

  19. mark replied on :

    Hello Doug i sourced these codes which gave tutorial about diffusion random walker . I don’t really understand some parts. can you clearify some points for me?

    % — Executes on slider movement.
    function slider_M_Callback(hObject, eventdata, handles)
    % hObject handle to slider_M (see GCBO)
    % eventdata reserved - to be defined in a future version of MATLAB
    % handles structure with handles and user data (see GUIDATA)
    M = get(handles.slider_M,’Value’);
    set(handles.value_M,’String’,round(max(M,1)));

    for the code above what does “round(max(M,1)” means

    codes 2

    M = round(max(get(handles.slider_M,’Value’),1));
    N_max = round(max(get(handles.slider_N,’Value’),1));

    part=[zeros(1,M);zeros(1,M)];
    move=mod(floor(4*rand(1,M)),4);

    N_size=40;
    part=[zeros(1,M);zeros(1,M)];
    plot(part(1,:),part(2,:),’o',’MarkerFaceColor’,'r’,'MarkerSize’,3,’MarkerEdgeColor’,'none’),…
    axis([-N_size N_size -N_size N_size]);
    hold on
    plot(part(1,1),part(2,1),’o',’MarkerFaceColor’,'b’,'MarkerSize’,3,’MarkerEdgeColor’,'none’);
    hold off
    datacursormode on

    Can you tell me what the above codes does. it was written under this fuction:
    function Diffusion_OpeningFcn(hObject, eventdata, handles, varargin)

  20. dhull replied on :

    @mark,

    The first gets the value of the slider, rounds it off and displays it.

    The second code is kind of taken out of context, I know it is getting values from the GUI and rounding them and plotting them.

    The best way to understand code like this is to run it with breakpoints at the lines you are trying to understand so that you can inspect each variable as the code is running. Then step through the code seeing what each line does.

    -Doug

  21. mark replied on :

    Thanks Doug, i have gained some understanding running the code with breakpoint at the lines. Doug do u know what this term does or mean? “isinf” examples of codes are:

    ym=isinf(1./move);
    xp=isinf(1./(move-1));
    yp=isinf(1./(move-2));
    xm=isinf(1./(move-3));

    And these terms “mod”, “floor” and “rand”. example

    move=mod(floor(4*rand(1,M)),4);

    Many Thx

  22. dhull replied on :

    @Mark,

    Where there is a command you do not recognise, you can type:

    >>doc ininf

    This will bring you to the documentation for that line, in this case to

    Doc for isInf
    http://www.mathworks.com/access/helpdesk/help/techdoc/ref/isinf.html

    Enjoy,
    Doug

  23. mark replied on :

    Many thanks Doug, You’re a life saver.

  24. mark replied on :

    Hello Doug, I am trying to run this code from the command window. But i keep getting this error saying:

    ??? Random variate function Z(t,X(t)) is invalid.

    here are the codes;

    >> N = 1; % Dimensions
    F = @(t,X) zeros(N,1); % Drift
    G = @(t,X) eye(N); % diffusion
    S = sde(F,G,’startState’,zeros(N,1));
    >> X = S.simByEuler(10000,’ntrials’,1,’Z',@(t,X) RandDir(N));

    comet(1:numel(X),X);
    plot(1:numel(X),X);
    grid on;

    ??? Random variate function Z(t,X(t)) is invalid.

    Please can you identify my mistake for me? Many Thanks

  25. dhull replied on :

    @mark,

    Please contact http://www.mathworks.com/support as I am not familiar with that toolbox, but we have support engineers who are.

    Thanks,
    Doug

  26. mark replied on :

    Thanks Doug…

  27. mark replied on :

    Hello Doug,
    I’m trying to plot series of ‘o’ points, But I can’t get the axes correctly. My GUI page has “axes1” and a “push Button” renamed as “start”. I have attached the M-File. How can i tell GUI that when i click on “run figure” from GUI, it should display an empty graph with “Y axes = -40: 40” and X axes = -40: 40”. (Can this code the put in the OpeningFcn?). The callback for the push button will plot series of points. How can get those points to be plot on my initial axes “-40:40” for both X and Y without changing the axes. I want to plot X and Y (as ‘o’) where X = -20:20 and Y = 0:0. Below is the M-File so far. Many thanks.

    function varargout = Work2(varargin)
    % WORK2 M-file for Work2.fig
    % WORK2, by itself, creates a new WORK2 or raises the existing
    % singleton*.
    %
    % H = WORK2 returns the handle to a new WORK2 or the handle to
    % the existing singleton*.
    %
    % WORK2(’CALLBACK’,hObject,eventData,handles,…) calls the local
    % function named CALLBACK in WORK2.M with the given input arguments.
    %
    % WORK2(’Property’,'Value’,…) creates a new WORK2 or raises the
    % existing singleton*. Starting from the left, property value pairs are
    % applied to the GUI before Work2_OpeningFcn gets called. An
    % unrecognized property name or invalid value makes property application
    % stop. All inputs are passed to Work2_OpeningFcn via varargin.
    %
    % *See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only one
    % instance to run (singleton)”.
    %
    % See also: GUIDE, GUIDATA, GUIHANDLES

    % Edit the above text to modify the response to help Work2

    % Last Modified by GUIDE v2.5 17-Oct-2009 10:42:20

    % Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct(’gui_Name’, mfilename, …
    ‘gui_Singleton’, gui_Singleton, …
    ‘gui_OpeningFcn’, @Work2_OpeningFcn, …
    ‘gui_OutputFcn’, @Work2_OutputFcn, …
    ‘gui_LayoutFcn’, [] , …
    ‘gui_Callback’, []);
    if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
    end

    if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
    else
    gui_mainfcn(gui_State, varargin{:});
    end
    % End initialization code - DO NOT EDIT

    % — Executes just before Work2 is made visible.
    function Work2_OpeningFcn(hObject, eventdata, handles, varargin)
    % This function has no output args, see OutputFcn.
    % hObject handle to figure
    % eventdata reserved - to be defined in a future version of MATLAB
    % handles structure with handles and user data (see GUIDATA)
    % varargin command line arguments to Work2 (see VARARGIN)

    % Choose default command line output for Work2
    handles.output = hObject;

    % Update handles structure
    guidata(hObject, handles);

    % set(handles.figure1,’Menubar’,'figure’);

    % UIWAIT makes Work2 wait for user response (see UIRESUME)
    % uiwait(handles.figure1);

    % — Outputs from this function are returned to the command line.
    function varargout = Work2_OutputFcn(hObject, eventdata, handles)
    % varargout cell array for returning output args (see VARARGOUT);
    % hObject handle to figure
    % eventdata reserved - to be defined in a future version of MATLAB
    % handles structure with handles and user data (see GUIDATA)

    % Get default command line output from handles structure
    varargout{1} = handles.output;

    % — Executes on button press in pushbutton1.
    function pushbutton1_Callback(hObject, eventdata, handles)
    % hObject handle to pushbutton1 (see GCBO)
    % eventdata reserved - to be defined in a future version of MATLAB
    % handles structure with handles and user data (see GUIDATA)
    axes(handles.axes1)
    %create a vector from 0 to 10, [0,1,2,3…10]
    x = -20:20;
    y = 0:0;
    plot(x,y, ‘o’,'MarkerFaceColor’,'r’,'MarkerEdgeColor’,'r’, ‘MarkerSize’,4);

  28. dhull replied on :

    @Mark

    You might want to try and get the plot working without the GUI first.

    
    x = -20:20;
    y = 0:0;
    plot(x,y, ‘o’,'MarkerFaceColor’,'r’,'MarkerEdgeColor’,'r’, ‘MarkerSize’,4);
    

    When doing the above, your “y” is a scalar (0). I doubt this is what you want.

    -doug

  29. mark replied on :

    Yes that’s exactly what I want. I want to get the ‘o’ either vertical (where all X values = 0) or horizontal (where all Y values = 0) Now if you look at the x-axes we have (x = -20:20) and the y-axes (y = -1:1). Is it possible to get both axes the same… say (both x & y will be -20:20). Also if you look at the graph, both the first dot and the last dot touch the boundaries of the graph. Is it possible to make the axes say x & y = -30:30, So that we will have 10 distance gap between the first dot and the boundary and last dots and the boundary. But if you reckon there is another easy way of doing it… please let me know

  30. mark replied on :

    Hello Doug,
    Many thanks for your reply. Please ignore the above question. I have resolved the problem. I have another question. I want to write a code under the pushbutton2_Callback)
    renamed as “RUN” (on GUI). I want to write a code to be able to move the points around. I sourced that I can either use any of these two codes/functions to do it. [V = h.move(position)], [V = move(h, position)].Please can you show me how to write these codes which will be controlled by the “RUN” push botton. The code should move the points to a distance of 0.5 from its original position to the left, right, up and down (just like a random walk). And they should continue to be moving until I click STOP push botton (pushbutton3_Callback). I have attached the M-File. Many Thanks

  31. dhull replied on :

    @mark

    That is a longer question than should really be answered in the comments to a blog. Let me give some outline:

    If you want the point to move until you click again, use a timer object and a toggle button to start and stop the timer.

    Use GET and SET to change the xdata and ydata properties of a line (a single point is still a line)

    For specifics, please see:

    http://www.mathworks.com/support

    Thanks,
    Doug

  32. mark replied on :

    Thank Doug for your respond. I have a question, say I have a dot/point on a graph with coordinates as (x=2, y=3) and I want to used GET and SET to tell GUI to move the point to (x=2.5, y=3.5).How do I write the code for this.

  33. dhull replied on :

    @mark

    h = line(2,4,'marker','o')
    x = get(h,'xdata')
    set(h,'xdata',x+0.5)
    

    Enjoy!

    Doug

  34. mark replied on :

    Many Thanks Doug, that was really helpful. But what does that 2,and 4 in the first line stands for? or what do they do.

  35. dhull replied on :

    @mark,

    2 and 4? Be adventurous, change them and find out! :) To end the suspense for those playing along at home, they are the x and y coordinates.

    Doug

  36. mark replied on :

    Thank Doug. You’re right; being adventurous is one of the greatest ways to learn. I’ve changed the code using 3 x values. it works fine. But I get a line joining the new points? i don’t know why. i wanted the old point to be deleted as soon as the new one is plotted. So I added this code (set(h.xdata,’delete’) but it didn’t work.

    
    y = [0,0,0];
    x=[0,10,20];
    h = line(x,y,'marker','o')
    x = get(h,'xdata')
    set(h,'xdata',x+4)
    set(h.xdata,'delete') %fail
    
  37. dhull replied on :

    @mark

    SET ‘lineStyle’ to ‘none’.

    There is no need to delete the old line, you are modifying the old line, so it should not be there anymore.

    If you really want to delete the old line, do not modify the ‘xdata’ (MATLAB gets confused if ‘xdata’ and ‘ydata’ are not matched up) Instead try this:

    
    set(h.xdata,'delete') %fail
    delete(h)             %win
    

    -Doug

  38. mark replied on :

    Thanks Doug, Don’t worry about the above question. (Thanks for your adventurous tip). After several trial-and-errors, I got it to work. Many Thanks Doug

  39. mark replied on :

    Thanks for your answer. Your suggestion is much easier and simpler than what I did. Thank you.

  40. mark replied on :

    Hello Doug
    I have seen your video about creating timer object/function in matlab command window. But please how do you create timer object/function to plot/move a point at (0,0)to any other random position on the graph in gui. I want to use toggle button to start and stop the timer. Please can you give the steps? I’ve seen doc timer note but I still can’t figure it out. Please. Thanks

  41. dhull replied on :

    @mark

    I need a more specific question. There are several steps here. Which is giving your problems?

    1.) Starting and stopping a timer- can you do this at the command line?

    2.) Starting and stopping a timer with a GUI- can you do this?

    3.) Moving a point using get and set- Can you do this at the command line?

    4.) Putting a callback in a timer- Can you do this to do something simple like displaying “Hello, World!”?

    Let me know what you have tried and your specific challenge.

    Doug

  42. mark replied on :

    1)Yes, i can start and stop a simple timer function at the command line.
    2)NO, i can’t start/stop timer in GUI.
    3)Yes, below is an example.
    >> size = 40;
    >> x = 0;
    >> y = 0;
    >> axis([-40 40 -40 40]);
    >> plot(x,y,’o');
    >> axis([-40 40 -40 40]);
    >> h = plot(x,y,’o');
    >> axis([-40 40 -40 40]);
    >> x = get(h,’xdata’)
    >> x=0;
    >> set(h,’xdata’,x+5);
    >>

    4)Yes, Make timer display “Hello World at the command line
    here is example
    >> t = timer

    Timer Object: timer-1

    Timer Settings
    ExecutionMode: singleShot
    Period: 1
    BusyMode: drop
    Running: off

    Callbacks
    TimerFcn: ”
    ErrorFcn: ”
    StartFcn: ”
    StopFcn: ”

    >> set(t,’executionMode’,'FixedRate’)
    >> set(t,’TimerFcn’,'disp(”Hello World”)’)
    >> start(t)
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    >> stop(t)

    But i don’t know how to Start and stop a timer with a GUI. Many thanks

  43. dhull replied on :

    @mark,

    My guess is that you can not find the timer to start and stop it. Have you used TIMERFIND?

    http://www.mathworks.com/access/helpdesk/help/techdoc/ref/timerfind.html

    Doug

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.