# MATLAB Basics: Setting a background image for a GUI 110

Posted by **Doug Hull**,

**Category:**- Format: Video,
- Level: Basic,
- Topic: GUI or GUIDE

## 110 CommentsOldest to Newest

**1**of 110

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

Thanks,

Craig

**2**of 110

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**of 110

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**of 110

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**of 110

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**of 110

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**of 110

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**of 110

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**of 110

Ed,

Please post your code for review.

Shorter and simpler is better for us to look at.

thanks,

Doug

**10**of 110

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**of 110

@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**of 110

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**of 110

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

**14**of 110

@vasso,

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

Doug

**15**of 110

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**of 110

@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**of 110

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**of 110

@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**of 110

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**of 110

@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**of 110

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**of 110

@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**of 110

Many thanks Doug, You’re a life saver.

**24**of 110

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**of 110

@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**of 110

Thanks Doug…

**27**of 110

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**of 110

@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**of 110

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**of 110

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**of 110

@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**of 110

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**of 110

@mark

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

Enjoy!

Doug

**34**of 110

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**of 110

@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**of 110

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**of 110

@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**of 110

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**of 110

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

**40**of 110

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**of 110

@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**of 110

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**of 110

@mark,

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

http://www.mathworks.com/help/releases/R2009b/techdoc/ref/timerfind.html

Doug

**44**of 110

Hello Doug,

Please I have a question, I used the codes below to plot a graph of particles at random location. Is there a simple way to plot vertical lines on the graph from 0 to 1 at an interval 0.05, without using all the “h=plot” codes I used below. It’s a bit long. Many thanks

function [x,y] = walker

n = 100; %number of particles

x = rand(n,1);

y = rand(n,1);

plot(x,y,’o’)

axis([0 1 0 1])

hold on

%plots the vertical lines

h=plot([.05 .05],[0,1],’k’);

h=plot([.1 .1],[0,1],’k’);

h=plot([.15 .15],[0,1],’k’);

h=plot([.2 .2],[0,1],’k’);

h=plot([.25 .25],[0,1],’k’);

h=plot([.3 .3],[0,1],’k’);

h=plot([.35 .35],[0,1],’k’);

h=plot([.4 .4],[0,1],’k’);

h=plot([.45 .45],[0,1],’k’);

h=plot([.5 .5],[0,1],’k’);

h=plot([.55 .55],[0,1],’k’);

h=plot([.6 .6],[0,1],’k’);

h=plot([.65 .65],[0,1],’k’);

h=plot([.7 .7],[0,1],’k’);

h=plot([.75 .75],[0,1],’k’);

h=plot([.8 .8],[0,1],’k’);

h=plot([.85 .85],[0,1],’k’);

h=plot([.9 .9],[0,1],’k’);

h=plot([.95 .95],[0,1],’k’);

hold off

**45**of 110

@Mark,

I like this file to do that:

http://www.mathworks.com/matlabcentral/fileexchange/1039

Doug

**46**of 110

Thanks so much Doug, the site was really helpful. I have a question. Having drawn the vertical lines, I have a subplot. I want to plot the number of particles in each cell/box/division on the subplot below. Example; say there are 5 particles in box1, then plot 5 on the y axis under box1 on the subplot. If there are 3 particles in box2, then plot 3 on the y axis under box2..and so on. Many Thanks

function [x,y] = walker

n = 100; %number of particles

x = rand(n,1);

y = rand(n,1);

t = subplot (2,1,1);

plot(x,y,’o’)

set(t,’Position’,[0.10 0.55 0.800 0.35])

axis([0 1 0 1])

hold on

number_cells =20;

for i=0:number_cells

plot([i/number_cells i/number_cells],[0,1],’k’);

end

hold off

ax2=subplot(2,1,2)

set(ax2,’Position’,[0.10 0.10 0.80 0.35]);

**47**of 110

@Mark

I think you want the command TEXT.

Doug

**48**of 110

Thanks for the reply Doug, but I’m not sure if TEXT command can be used. Maybe I didn’t explain well. Let say there are two points on plot_1. Then in plot_2, I want to plot (y=2, x=0), if there are 3 points, plot on PLot_2(y=3, x=0). So always the number of points in plot_1 will be the y values in plot_2. Let say x is 0. My problem is how do I write the function to plot on Plot_2 using the example above. Many thanks

**49**of 110

@mark,

Why not use the plot, or line command?

Doug

**50**of 110

Thanks Doug for your reply, I have a question. I plotted 4 points on a graph [plot(x,y,’o’)]. How can i write a code to tell me how many points i have plotted on the graph. Many Thanks

like: plot(x,y,’o’)

count number of points

**51**of 110

Mark,

>>numel(x)

will tell you the NUMber of ELements in x.

Doug

**52**of 110

Many Many thanks Doug, the numel function is REALLY helpful. Doug, say i draw a line at the center of a plot to divide the plot area(i.e. cell_1 and cell_2) How can i use numel, to say show numel(x) for cell_1 and show numel(x) for cell_2. Many Thanks

**53**of 110

Hello Doug, I’m trying to used HIST FUNCTION to plot the number of points in each of the cell above. I’ve a plot but it doesn’t look right. Please i need a little help. Many thanks

n = 1000;

x = rand(n,1);

y = rand(n,1);

subplot(2,1,1)

axis([0 1 0 1]);

plot(x,y,’.’);

hold on

number_cells =20;

for i=1:number_cells

plot([i/number_cells i/number_cells],[0,1],’k’)

end

hold off

subplot(2,1,2)

density = hist(x,number_cells);

edges = 0.05:20; %edges of the number_cells

plot(edges,density)

**54**of 110

@Mark,

Not sure what you are doing wrong there. It was easier just to do it my way.

clear clc minX = 0; maxX = 1; numPoints = 10; numBins = 3; binEdges = linspace(minX, maxX, numBins+1) binWidth = binEdges(2) - binEdges(1); binCenters = linspace(binWidth/2, maxX-binWidth/2, numBins) x = minX + rand(1,numPoints)*(maxX - minX) y = rand(1,numPoints); [binCount, binCenters] = hist(x, binCenters) subplot(2,1,1) plot(x,y,'.', ... [binEdges; binEdges], [zeros(size(binEdges)); ones(size(binEdges))],'k-' ) xlim([minX maxX]) ylim([0,1]) subplot(2,1,2) plot(binCenters, binCount) xlim([minX maxX])

**55**of 110

Many Thanks Doug… You’re a life saver. I got better underdtanding now. Many Thanks.

**56**of 110

Hello Doug,

I have a question. I made a loop similar to the codes above to run for 100 steps. I opened the right hand side wall/boundary of subplot (2,1,1), which allows some of the points to go beyond the last bin. The problem is, anytime I run subplot (2,1,2), the plot for the first and second bins comes fine, but the problem is with the third bin. It always adds the other points that went beyond the wall to the current points in the last bin before plotting. I want it to plot ONLY the points currently in the last bin. And any point the goes beyond the wall should be ignored when plotting the graph in subplot (2,1,2) . Many thanks

**57**of 110

@mark,

I do not understand the question. Please post or e-mail simplified code.

Doug

**58**of 110

Hello Doug,

My codes are below. It runs for 100 steps. How can I open the right hand side boundary/wall of subplot 1 so that some of the points can go beyond maxX (maxX=1) (like making them move randomly into infinite). Now all the points are contained in the boundary where minX and maxX = [0,1] respectively. I want them to be able to continue their random walk within the 100 steps beyond the boundary through the right hand side without being restricted by the boundary. Many Thanks

clear

clc

minX = 0;

maxX = 1;

numPoints = 20;

numBins = 10;

binEdges = linspace(minX, maxX, numBins+1);

binWidth = binEdges(2) – binEdges(1);

binCenters = linspace(binWidth/2, maxX-binWidth/2, numBins);

x = minX + rand(1,numPoints)*(maxX – minX);

y = rand(1,numPoints);

[binCount, binCenters] = hist(x, binCenters);

subplot(2,1,1)

plot(x,y,’.’, …

[binEdges; binEdges], [zeros(size(binEdges)); ones(size(binEdges))],’k-‘ )

xlim([minX maxX])

ylim([0,1])

subplot(2,1,2)

plot(binCenters, binCount)

xlim([minX maxX])

for i = 1:100

binEdges = linspace(minX, maxX, numBins+1);

binWidth = binEdges(2) – binEdges(1);

binCenters = linspace(binWidth/2, maxX-binWidth/2, numBins);

x = minX + rand(1,numPoints)*(maxX – minX);

y = rand(1,numPoints);

[binCount, binCenters] = hist(x, binCenters);

subplot(2,1,1)

plot(x,y,’.’, …

[binEdges; binEdges], [zeros(size(binEdges)); ones(size(binEdges))],’k-‘ )

xlim([minX maxX])

ylim([0,1])

title(sprintf(‘Number of Steps : %d’,i))

subplot(2,1,2)

plot(binCenters, binCount)

xlim([minX maxX])

length (find(0 < x))

pause(.1);

end

**59**of 110

@Mark,

You could simply change the maxX value in the loop as you need. Is that what you are talking about?

Doug

**60**of 110

Thank Doug,

But I wanted the minX and maxX values to stay the same. I don’t really want to see the points the goes beyond maxX. Only I wanted them to have the tendency to go beyond the maxX. Many Thanks

**61**of 110

@Mark,

What does it mean to “Not go beyond the maxX” but “have the tendency to go beyond the maxX”?

Doug

**62**of 110

Thanks Doug,

Sorry, I meant the points should have the tendancy to move randomly beyond maxX. Many thanks..

**63**of 110

@Mark,

Why does changing maxX NOT give you what you desire?

Doug

**64**of 110

Thanks Doug,

May be I’m not explaining my question well. Let’s take it like this. Say we have a box or field containing 100 random walkers. The boundary of the field is (0 1 0 1) and it CANNOT be changed. But the walker are ALLOWED to continue their random walker beyond the axis (0 1 0 1). Meaning they can go over or beyond this axis, but the axis WILL STAY THE SAME.

Now let say we run this simulation for 100 steps, after 100 steps any walker that is outside the field would be discarded. (I think this is where I’m been misunderstood, what I meant is, say if at the end of the 100 steps, the number of walkers in the field is 90 (instead of 100), then we’ll assume that 10 walkers went over the field and did not return)

And any walker that goes over or beyond the field and fails to return after the 100 steps would be discarded.

Doug, I feel if you understand me here then you can help me. Many thanks Doug

**65**of 110

density = hist(x(0 > x x<1)] please can you help me write the range for x. Many thanks

**66**of 110

@Mark,

vi = (x > 0) & (x < 1); hist(x(vi)) That should work. Doug

**67**of 110

Many Thanks Doug… You’re a life saver

**68**of 110

Hi Doug,

Compliments!

Sorry, i have a problem.

I’ll need a correct synatx to do a particular computation.

I have 2 vectors A and B.

A = [2.7664 – 1.6127i

5.7282 – 4.7690i

6.6023 – 4.7755i

6.3574 – 2.9875i

5.0828 – 5.3947i

6.5345 – 4.3115i

5.6271 – 2.5061i

5.4990 – 2.0237i

8.3190 – 4.1162i

8.4187 – 1.1449i]

and B = [2.5350 – 1.5107i

5.8623 – 2.1677i

6.8089 – 2.0042i

6.4350 – 0.9318i

5.0570 – 1.6143i

6.3782 – 1.6191i

5.3868 – 0.3930i

5.3829 – 0.2981i

8.1315 + 0.5634i

7.8706 – 2.7222i]

i want to write a simple code that receives a input, say, [2,5,8] and it’ll sum the values of the 2nd, 5th and 8th rows of A and divide the resulting value with the result of the sum of the 2nd, 5th and 8th of B.

this should also allow for any number of inputs.

Thanks for your anticipated help!

**69**of 110

Try this after A and B are defined:

vi = [2 5 8] num = sum(A(vi)) den = sum(B(vi)) answ = num/den

**70**of 110

Hello Doug,

I used the codes below to plot a straight line graph. I’ve removed the fault SQUARE BOX surrounding the plot. Now I want to manually plot 4 lines to make a BOX around my plot. How do I plot the UPPER & LOWER horizontal lines and LEFT & RIGHT VERTICAL to form a BOX. Many Thanks

x = 1:10;

y = x.^2;

plot(x,y,’o’)

set(gca,’YTickLabel’,”,’XTickLabel’,”);

set(gca,’xcolor’,[1 1 1])

set(gca,’ycolor’,[1 1 1])

**71**of 110

@Mark

Have you used the rectangle or line functions?

Doug

**72**of 110

Hello Doug,

I have a program which plots number of point (N). Initial I set N=10. And everything works fine. I designed a user interface with MATLAB GUI. I want to give user the chance to enter any number of points to plot. I used “edit text function”. Please how can I tell the program to get the number of point (N) to plot from the edit text space? That’s the number that the user enters in the edit text in GUI. Many thanks

**73**of 110

@mark,

numToCountTo = get(handles.edit1, ‘value’)

in any of the automatically created callbacks, you should be given the handles structure. That contains the handles to all graphical objects in your GUI. Doing something similar to the above should get you what you want.

Doug

**74**of 110

Hello Doug,

Don’t worry about my question above. i have been able to do it. Many thanks

**75**of 110

Thanks for answering Doug. Your solution is very short and simple. I’ve gained better understanding now. Many thanks

**76**of 110

Hello Doug,

I created 10 random walkers that takes 5 steps each time i run the program in matlab gui. I have created a checkbox, and i said if the checkbox is ticked, plot a hist plot showing the direction of movements of one of the particles. I also said that when the box is unchecked it shouldn’t plot the HIST PLOT. So far everything works fine. My question is, how can i say that anytime i uncheck the checkbox, matlab should clear the previous hist plot from its memory so that when i check it again, it’ll not show or continue from the position (the hist plot) it was before i unchecked it. But it’ll plot a new hist plot

Many thanks

**77**of 110

@mark,

There is a callback on the checkbox. When you check (or uncheck) it, the callback will fire. Test the ‘value’ of it and take appropriate action.

Doug

**78**of 110

Thanks Doug,

Well i made, if checkbox is checked, value = 1, and if unchecked value = 0. I meant it works fine. It plot and unplot very well. The problem is, it looks like when i uncheck it. it only hides the hist plot, then when i check it again it shows the hist plot from step one. What i want is, when i uncheck it should delete or clear the hist plot. and when i check it again, it should show the current move hist plot without showing the previous plot when i unchecked it

this is the code i used

if (get(handles.checkbox1,’Value’) == 1)

plot(hist_x,hist_y,’b’);

else

clear plot(hist_x,hist_y,’b’);

end

Many thanks

**79**of 110

@mark

Without seeing your code, I can not answer for sure, but you likely want CLA to CLear Axis

Doug

**80**of 110

Thanks Doug,

I really appreciate your help. I have a pushbutton. i want to use it to terminate my loop. pushbutton2 is the button i want to use to terminate the loop. Pushbutton1 Runs the loop.

So in pushbutton callback

function pushbutton1_Callback(hObject, eventdata, handles)

for i = 1:steps

%I put the code below to terminate the program when i pressed pushbutton2. but it’s not working.

if (get(handles.pushbutton2,’Value’) == 1)

break;

end

**81**of 110

@Mark,

The pushbutton is not what you want, try a toggle button.

Doug

**82**of 110

Many Thanks Doug

Toggle button works great. You’re a life saver. Many thanks

**83**of 110

Hi Doug,

n = 100;

x = rand(n,1);

y = rand(n,1);

axes(handles.axes1);

plot(x,y,’o’)

I used the codes above to plot a simple random points in gui.I also have a checkbox function. I have these codes for the checkbox. I said if checkbox value = 1; plot this line at the centre of the graph {plot([0.5 0.5],[0,1],’k’);} and it works fine. My question is, how can i say, if the line is plotted, delete all the points that are behind the line on the left.

Many Thanks

**84**of 110

@mark

This will be a little tricky, but not too bad. You will need the handle to the plot

h = plot(x,y,’o’)

You could find it at the child of that axes also. Anyways, once you have it, you should get the xdata and ydata from it.

Look for the indices of the xdata that are less than your threshold. Once you have these indices, set the xdata and ydata back into the plot without those values. Check this oldie but goodie out!

http://blogs.mathworks.com/videos/2006/11/06/more-mini-videos/

**85**of 110

Thanks very much for your respond Doug. I tried your example, i have a question

here are the codes i used.

>> n = 100;

>> x = rand(n,1);

>> y = rand(n,1);

>> h = plot(x,y,’*’);

>> x=get(get(h,’children’),’xdata’)

x =

[]

>> y=get(get(h,’children’),’ydata’)

y =

[]

>> ind= find(x>

The value on both x and y axes on the plot is

[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1]; but i don’t know why i get [] as an output to { xi=get(get(h,’children’),’xdata’)} and the indices. Please where did i go wrong?

Also i used this method:

>> axes

>> get(gca,’children’)

ans =

Empty matrix: 0-by-1

>> allchild(gca)

ans =

191.0017

190.0028

189.0027

188.0028

Many thanks

**86**of 110

@mark

You do not need to get the children. Try this:

get(h,’xdata’)

**87**of 110

Hello Doug

I have edit text box in matlab gui, where user can enter and number between 1 and 100. How can i let the program check user input. I have already set the max and min numbers, but i want to check for letters input. Assuming user input letters instead of NUMBERS. I want the program to give a warning… Warning like..”Please input MUST be a NUMBER”

Many Thanks

**88**of 110

@mark,

On the callback for the edit box, you can put validation code. You can check to see if it is a string, to see if the value is in range, etc…

Doug

**89**of 110

Many Thanks Doug, That was really helpful. I have a question.I have a while loop that loops for 10 steps (or 10 times) when i click on the button ‘GO’. I have another button called ‘One Step’ How can i say that if i click of the ‘One step’ button, it should run ‘One step’ then break, when i click again it run the 2nd step then break. So basically using the one step to manually run the loop step by step. but when i click on ‘GO’ it should run all the 10 steps. many thanks

**90**of 110

@Mark,

The newest video:

http://blogs.mathworks.com/videos/2010/03/19/break-and-continue/

Might help.

Basically though, I would have the three buttons all call the same code with an input to the callback. that input would represent the number of time to run the loop.

Doug

**91**of 110

Many thanks Doug.

Doug, is it possible to format a warning or popup message. Coz i keep getting this error message “Too many input arguments”.

here is my code

uiwait(warndlg(‘Choose A Colour’,’FontWeight’,’bold’,’!! Warning !!’,’modal’));

Many thanks

**92**of 110

@Mark,

I did not see anything in the documentation that allows you to specify font weight. Take that out and the ‘!! warning !!’ as you can only specify one string. Or put in a cell array to get two lines.

Doug

**93**of 110

Great! thanks Doug,

I have a button in my gui, which i want to use to disp or open a *.fig file saved in the same folder with the main program. The name of the figure is ‘Picture’ I used uiopen(‘Picture.fig’). But when i clicked on the button, it opens a file selection dialog from which a user can select the file to open. My question is, is there any way or function available that will open the file (figure) itself when the button is clicked? I mean i don’t want user to see the file path, what i want is, when user click on the button, the ‘picture figure’ will open or appear, and not the file select window. I also tried uigetdir, uiputfile and uigetfile, but they produced the same output. Sorry for the long words. Many thanks

**94**of 110

@Mark,

Try

open(‘untitled.fig’)

Doug

**95**of 110

Million thanks Doug, You’re a life saver… Thanks Mate

**96**of 110

Hi Doug,

I have produced a user program in gui, which contains parameter box and axes1. The plot looping can be stopped or paused by the user. Now i want to add the possibility of saving the plot. I want this to be available when user pause the program then he/she can save the plot. I have tried several saving methods, but the output always saves the whole gui window, thus the plot and the parameter box. i want to save only the plot in say, jpg or fig or something like that.

Here is my plot

axes(handles.axes1)

plot_walker(x,y,’o’)

i used functions like,

saveas(plot_walker,’New.jpg’)

saveas(axes1,’New.jpg’)

i also tried [hgsave(‘filename’)]

but i can’t get ONLY the plot saved. Many thanks

**97**of 110

@mark,

There is not a real direct way of saving just an axes out of a GUI. You could reparent the axes to a new figure, then save the figure as normal. some variant on that idea would be your best bet.

Doug

**98**of 110

Thanks Doug, for the reply. I used the codes below to make duplicated plot at the command window.

n = 100;

x = rand(n,1);

y = rand(n,1);

h1 = plot(x,y,’o’);

h1=gcf;

h2=figure;

objects=allchild(h1);

copyobj(get(h1,’children’),h2);

But how can i use this in gui. I want to put it under a pushbutton callback. i want it to double plot the plot on axes1. But anytime i run it, i get this error saying…

??? Undefined function or variable ‘axes1’.

Error in ==> program>pushbutton1_Callback at 106

h1=axes1;

here is my code

function pushbutton36_Callback(hObject, eventdata, handles)

n = 100;

x = rand(n,1);

y = rand(n,1);

axes(handles.axes1)

h1 = plot(x,y,’o’);

h1=axes1;

h2=figure;

objects=allchild(h1);

copyobj(get(h1,’children’),h2);

**99**of 110

sorry for using pushbutton1 in the error message (for the above question), it was meant to be pushbutton36

**100**of 110

@mark,

This is a little involved for blog comments… :)

please contact http://www.mathworks.com/support

Doug

**101**of 110

Many Thanks Doug,

I have been able to do it now. Thanks for your idea. Many thanks

**102**of 110

Hello Doug,

I’m using MATLAB Version 7.8 (R2009a). My laptop is intel Core2 Duo, CPU T6400 @ 2.00GHz. 3.0GB RAM and 200GB hard drive with NVIDIA graphic card. My pc spec surpasses the recommended system requirement for running matlab 2009a. But why is working in gui so slow. Even if I’m running matlab alone with no other application, working in gui is still slow. Please is there anything i can do to enhance the performance. Many thanks

**103**of 110

@Mark,

I need more information to really diagnose this.

contact http://www.mathworks.com/support

Thanks

Doug

**104**of 110

Hello Doug,

I have displayed an image in my gui program using your tutorial above. “imshow” method. The image has a white background. Is there a way to make the image transparent? Many Thanks

**105**of 110

@Mark,

h = imshow(magic(500)) set(h,'alphaData',round(rand(500))) set(h,'alphaDataMapping','none')

Take a look at this example.

Doug

**106**of 110

Hello Doug,

I was able to set a background image with the images which are

already in the \toolbox\images\imdemos\ but when I tried to create my own image and saved it there I got errors and X/Y plot displayed. Do you know what seems to be the problem?

thanks

**107**of 110

@Yonatan,

I think I would need to see the code. Please send via e-mail.

Doug

**108**of 110

I am trying to place an image with another axes plotting my data at the same time. Unfortunately code plots on axes2 instead of axes1. How do we separate their inputs?

% — 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

% — Executes during object creation, after setting all properties.

function axes2_CreateFcn(hObject, eventdata, handles)

% hObject handle to axes2 (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 axes2

axes(hObject)

imshow(‘bau.tif’)

**109**of 110

Pretty component to content. I simply stumbled upon your blog and in accession capital to claim that

I get actually enjoyed account your weblog posts. Anyway I will be subscribing

on your augment or even I achievement you get admission to consistently rapidly.

**110**of 110

Sir i am doing mtech project in medical field by using matlab software 2009a the topic is luekemia by reading no of papers in ieee i got some information and the main problem i am getting through my project is GUI and erode to gray convertion for an image so please can you help me out from this problem

## Recent Comments