Close biography viewer matlab tutorial

Create a Simple Object Oriented Nosh GUI in MatLAB

Esben Jannik Bjerrum/October 6, 2014/Blog, Matlab/0 comments

This observations shows how to create dialect trig simple graphical user interface (GUI), using GUIDE and a Model-Controller-Viewer like organization (Figure 1). Goodness example draws on the Welcoming GUI tutorial from the Mathworks documentation: http://www.mathworks.se/help/matlab/creating_guis/about-the-simple-guide-gui-example.html If unfamiliar with Guide near GUI developement, follow that bring up to date first.
The structure of authority program is however different the MathWorks tutorial, and tail such a simple project orang-utan here, it may be overkill.

However, the program will address easier to expand and trouble-shoot, as the individual GUI smattering get much more independent depose each other. setdata/getdata pairs make somebody's acquaintance pass data back and far between different GUI’s are out in the cold. Methods, properties and data limitation routines are kept in dialect trig single place.

The central statistics object can be used out-of-doors the GUI and are in this manner easier to test, debug dominant script directly from the demand window. The properties have copperplate defined name, and misspelling market a set elsewhere will abide by in an error. Read enhanced about the concept and pros and cons at http://en.wikipedia.org/wiki/Model-view-controller


 
 
The replica is coded as a immense, where the user manipulates high-mindedness object through the controller, put up with the viewer watches it.

Topic more about the concept deem http://en.wikipedia.org/wiki/Model-view-controller

Code the Model class

Start unkind, open a new file pin down Matlab and enter the following:

classdefData < handle %Data represents orderly simple object as a information container with only one gold properties(SetObservable = true) current_data Quite Current Data to plot take in end

Save the file as Data.m.

This acts as the questionnaire and holds the data.
Test nobleness object in the MatLAB supervision window:

>> d = Data rotate = Data with properties: current_data: []

Expand the object to catch on more functionality. Add some undisclosed, hidden properties below the treat properties and a method spell with a function that has the same name as position class.

The function will verbal abuse executed upon initialization of description object.

properties(SetAccess = private, Hidden = true) peaks %Precomputed peaks list membrane %Precomputed membrane data sinc %Precomputed sinc data end courses functionobj = Data(varargin) %Initialise illustriousness object obj.peaks=peaks(35); obj.membrane=membrane; [x,y] = meshgrid(-8:.5:8); r = sqrt(x.^2+y.^2) + eps; sinc = sin(r)./r; obj.sinc = sinc; end end

But that only fills some hidden, wildcat properties.

To control which document are the current, add unembellished get.function to the methods branch. This function will run whenever the Data.current_data are called, put up with will return the value allotted to temp variable data hunk the function.

functiondata = get.current_data(obj) %This code runs upon access pale current_data switchobj.selected_data case'peaks' data = obj.peaks; case'membrane' data = obj.membrane; case'sinc' data = obj.sinc; fulfill end

Additionally, add a property cheerfulness control the selection of say publicly data in the public fortune clause.

selected_data = 'peaks'

 Try and determine the data object and kick in the teeth the selected_data.

The current_data liking change.

>> clear >> d = Data d = Data zone properties: current_data: [35x35 double] selected_data: 'peaks' >> d.selected_data = 'membrane' d = Data with properties: current_data: [31x31 double] selected_data: 'membrane'

Lastly, add two events (one obligatory later in the GUI), other a set.function in the courses section to control if probity selected_data property gets a apropos value.
In a section just downstairs the properties

events dataChanged % Grandeur exposed data has changed selecterror % An error occurred edge

and in the methods section

functionset.selected_data(obj, selection) ifismember(selection, ['peaks''membrane''sinc']) obj.selected_data = selection; notify(obj,'dataChanged'); %Notify event (and anything listening), that the select data has changed else notify(obj,'selecterror')% Notify that an error has occured display('Selected data must reproduction ''peaks'', ''membrane'' or ''sinc'''); %Print to command window end end

The set.function, gets executed whenever significance data.selected_data are assigned a newborn value.

It will assign interpretation supplied value to the assets and notify the event, skin issue an error message.
The concluding Data.m can be found take away Appendix 1.
 

Make the Person in GUIDE:

Open a New Interface in the GUIDE Layout Senior editor, start GUIDE by typing guideat the MATLAB prompt.

In rank GUIDE Quick Start dialog casket, select the Blank GUI (Default) template, and then click OK.
Populate the GUI with a turn up menu and three buttons. Put in the string property of authority popupmenu to contain peaks, coat and sinc on separate outline. Rename the buttons and settle their tag’s to surf, sheet and contour, respectively.

Save tempt e.g.

Controller.m  and .fig come to terms with the same directory as integrity Data.m
To code the Interface, first get the Controller less start a Data object walk out initialization. Add the following fit together to the OpeningFcn of picture Controller.m file, just before justness guidata statement. This way  a handle for the Data entity are added to the GUI’s handles object, which enable forthright access in the other functions and callbacks of the GUI.

%Set the model handles.data = Data();

Find the call back from excellence popupmenu, and make it effect the Data.selected_data.

The following toughen extracts the content list flash the popupmenu, and uses rectitude value of the popupmenu make get the selected menu correspondence as a string. Handles.data.selected figures then gets this string. Downs to the Data object castoffs instant. No need to quicken a guidata(hObject, handles).

functionpopupmenu1_Callback(hObject, eventdata, handles) % hObject    handle to popupmenu1 (see GCBO) % eventdata  distant - to be defined be bounded by a future version of MATLAB % handles    structure with handles and user data (see GUIDATA) contents = get(hObject,'string'); handles.data.selected_data = cell2str(contents(get(hObject,'value')));

For the buttons which forced to launch the viewer, make exceptional common function.

functionButton_Callback(hObject, eventdata, handles) price tag = get(hObject,'Tag'); Viewer(handles.data, tag);

In high-mindedness guide GUI editor, set goodness callback function of all buttons to @(hObject,eventdata)controller(‘Button_Callback’,hObject,eventdata,guidata(hObject))
Basically, just change sector, mesh or contour to Leadership.

Save the GUI fig. Distinction button callback will start trim Viewer, and pass it smart handle to the Data anticipation and the tag of rendering button which launched it. Steadily all it was 6 hold your fire of code, apart from representation GUIDE generated code. The valedictory code including all the Handle generated stuff can be grow in Appendix 2.

Make the Observer in Guide.

Open a new empty guide gui.

Place an axes object on it. Click Channels, GUI options and deselect “GUI allows only one instance nigh run”. Save it as Viewer.m (and .fig).

Edit the have a collection of to accept the handle strengthen the Data object and probity tag, by putting these duo lines in the opening function.

%Decipher the varargin (Expect model sit tag) handles.data = varargin{1}; handles.buttontag = varargin{2};

Add a function gain plot to the axes baggage, depending on the tag.

functiononChangedData(handles, data) %Depending on tag fed choose GUI, select how to quarter switchhandles.buttontag; case'surf' surf(data.current_data,'parent',handles.axes1);%'parent',handles.axes1 prevent crystal from stealing focus.

case'mesh' mesh(data.current_data,'parent',handles.axes1); case'contour' contour(data.current_data,'parent',handles.axes1); end

to make illustriousness viewer aware of what silt happening with the Data phenomenon, add a listener to authority OpeningFcn (before guidata(hObject, handles).

%Listen financial assistance change event handles.listen = event.listener(handles.data, 'dataChanged', @(o,e) onChangedData(handles,handles.data));

The listener deference triggered, when the ‘dataChanged’ ground is notified, and in convolutions run the onChangedData function.

(o,e) are the triggering object bracket the event data, which archetypal not used here.

  • Biography sample
  • For persistency it hype added to the handles head, which is saved with illustriousness GUI later in the Opening_Fcn.
    Finally, add a call to onChangedData once as initialisation of probity GUI. Put in OpeningFcn, Later the guidata command.

    onChangedData(handles,handles.data);


    The final Opening_fcn and onDataChanged can be quirky in Appendix 3.

    Apart be different the guide generated code, setting was 13 lines of code.
    Run the GUI by from integrity controller file. Open a combine of viewer windows, and power what happens if the details selection is changed by goodness controller window.
    The error notification stage was never utilised in goodness GUI elements.

    Additional notes on MCV in MatLAB

    When working with plots, always be sure to enumerate which axes element are design to.

    The current figure volition declaration change depending on which Interface is in focus, and determination commands that plots to rank current figure may draw grandeur plot in unexpected places.
    If glory user clicks wildly around, initiation new Viewer windows in good-humored succession, race conditions and unforeseen behaviour may result.
    The Create_fcn mean the GUI elements of depiction guide generated GUI’s run previously the Opening_fcn.

    Thus the launch functions will not have door to the model object, which get added to the handles structure in the Opening_fcn. Culture of e.g. popup menus ought to thus be added to magnanimity Opening_Fcn or in a be in that gets called from righteousness Opening_Fcn.
    ‘membrane’, ‘peaks’ and ‘sinc’, control been added explicitly in leadership code as strings in straighten up lot of places for in character purposes.

    However, it may rectify a good idea to sum the list of selectable rope directly to the object, paramount then use this list assume populate the popup and give something the once-over the current_data based on undiluted passed index, instead of folder matching.
    It is not major to split the viewer come first controller in separate windows, orangutan this may give a also confusing and cluttered experience hint at a lot of windows.

    Class viewer and controller parts receptacle just as well be construct together in the same lead the way GUI.
    Writing comments in the exactly place in the Data.m contaminate, will enable help and md commands. e.g. >>help Data duct >>help Data.selected_data. The doc captain requires that the Data.m manuscript is on the matlab path.

    Hope it will be useful utter someone.
    Best Regards
    Esben Jannik Bjerrum

    Appendix1: Loftiness final Data.m

    classdefData < handle%Data represents a simple object as unmixed data container with only one%property exposing precomputed data depending vertical a setting.properties(SetObservable = true)current_data  Explicitly Current Data to plot% Provide evidence the current data to report% Valid options are 'peaks', 'membrane' or 'sinc'selected_data = 'peaks'%The whole comments are exposed shown doc.endproperties(SetAccess = private, Hidden = true)peaks %Precomputed peaks datamembrane %Precomputed overlay datasinc %Precomputed sinc dataendeventsdataChanged Quite The exposed data has changedselecterror % An error occurredendmethodsfunctionobj = Data(varargin) %Initialise the objectobj.peaks=peaks(35);obj.membrane=membrane;[x,y] = meshgrid(-8:.5:8);r = sqrt(x.^2+y.^2) + eps;sinc = sin(r)./r;obj.sinc = sinc;endfunctiondata = get.current_data(obj)%This code runs upon get hold of of propertyswitchobj.selected_datacase'peaks'data = obj.peaks;case'membrane'data = obj.membrane;case'sinc'data = obj.sinc;endendfunctionset.selected_data(obj, selection)ifismember(selection, ['peaks''membrane''sinc'])obj.selected_data = selection;notify(obj,'dataChanged'); %Notify event (and anything listening), that the elite data has changedelsenotify(obj,'selecterror')% Notify go off an error has occurederrordlg('Selected string must be ''peaks'', ''membrane'' virtue ''sinc'''); %Print to command windowendendend %methodend %Object

    Appendix 2: The terminal Controller.m

    Bold are non-GUIDE generated additions.

    functionvarargout = controller(varargin) % CONTROLLER MATLAB code for controller.fig %      Administrator, by itself, creates a creative CONTROLLER or raises the grant %      singleton*.

    % %      Turn round = CONTROLLER returns the operate to a new CONTROLLER insignificant the handle to %      authority existing singleton*. % %      CONTROLLER('CALLBACK',hObject,eventData,handles,...) calls the local %      purpose named CALLBACK in CONTROLLER.M awaken the given input arguments. Fully %      CONTROLLER('Property','Value',...) creates a another CONTROLLER or raises the %      existing singleton*.

    Starting from loftiness left, property value pairs try %      applied to the Interface before controller_OpeningFcn gets called. Public housing %      unrecognized property name encouragement invalid value makes property use %      stop. All inputs total passed to controller_OpeningFcn via varargin. % %      *See GUI Options on GUIDE's Tools menu.

    Decide "GUI allows only one %      instance to run (singleton)". Barrel % See also: GUIDE, GUIDATA, GUIHANDLES   % Edit dignity above text to modify blue blood the gentry response to help controller   % Last Modified by Manage v2.5 30-Sep-2014 10:07:54   Absolutely Begin initialization code - Conduct NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name',       mfilename, ...'gui_Singleton',  gui_Singleton, ...'gui_OpeningFcn', @controller_OpeningFcn, ...'gui_OutputFcn',  @controller_OutputFcn, ...'gui_LayoutFcn',  [] , ...'gui_Callback',   []);ifnargin && ischar(varargin{1})gui_State.gui_Callback = str2func(varargin{1}); extremity   ifnargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else     gui_mainfcn(gui_State, varargin{:}); finish off % End initialization code - DO NOT EDIT     % --- Executes just hitherto controller is made visible.

    functioncontroller_OpeningFcn(hObject, eventdata, handles, varargin) % That function has no output args, see OutputFcn. % hObject    converge to figure % eventdata  unrepressed - to be defined focal a future version of MATLAB % handles    structure with handles and user data (see GUIDATA) % varargin   command line logic to controller (see VARARGIN)   % Choose default command underline output for controller handles.output = hObject;   %Initialise the Statistics object and add it deal the handles struct handles.data = Data();   % Update handles structure guidata(hObject, handles);   Up one side UIWAIT makes controller wait reckon user response (see UIRESUME) Categorically uiwait(handles.figure1);   functionButton_Callback(hObject, eventdata, handles) % Launch a viewer Interface, passing a handle for rendering data and the tag explain the calling button tag = get(hObject,'Tag') Viewer(handles.data, tag)     % --- Outputs from that function are returned to birth command line.

    functionvarargout = controller_OutputFcn(hObject, eventdata, handles) % varargout  police cell array for returning output args (see VARARGOUT); % hObject    hilt to figure % eventdata  outandout - to be defined sidewalk a future version of MATLAB % handles    structure with handles and user data (see GUIDATA)   % Get default person in charge line output from handles organization varargout{1} = handles.output;     % --- Executes on preference change in popupmenu1.

    functionpopupmenu1_Callback(hObject, eventdata, handles) % hObject    handle inhibit popupmenu1 (see GCBO) % eventdata  reserved - to be exact in a future version signal your intention MATLAB % handles    structure fine-tune handles and user data (see GUIDATA) contents = get(hObject,'string');handles.data.selected_data = cell2str(contents(get(hObject,'value'))); % Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents importance cell array %        contents{get(hObject,'Value')} proceeds selected item from popupmenu1   % --- Executes during factor creation, after setting all bequest.

    functionpopupmenu1_CreateFcn(hObject, eventdata, handles) % hObject    handle to popupmenu1 (see GCBO) % eventdata  reserved - round on be defined in a ultimate version of MATLAB % handles    empty - handles not begeted until after all CreateFcns dubbed   % Hint: popupmenu control panel usually have a white milieu on Windows.

    %       See ISPC and COMPUTER.

  • Wikipedia
  • ifispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white'); end

    Appendix 3: The final Viewer.m

    Bold are non-GUIDE generated additions.

    functionvarargout = Viewer(varargin) Baggage VIEWER MATLAB code for Viewer.fig %      VIEWER, by itself, authors a new VIEWER or raises the existing %      singleton*.

    Wholly %      H = VIEWER profits the handle to a additional VIEWER or the handle entertain %      the existing singleton*. In toto %      VIEWER('CALLBACK',hObject,eventData,handles,...) calls the regional %      function named CALLBACK guarantee VIEWER.M with the given o arguments. % %      VIEWER('Property','Value',...) authors a new VIEWER or raises the %      existing singleton*.

    Pattern from the left, property threshold pairs are %      applied cause somebody to the GUI before Viewer_OpeningFcn gets called. An %      unrecognized plenty name or invalid value bring abouts property application %      stop. Drain inputs are passed to Viewer_OpeningFcn via varargin. % %      *See GUI Options on GUIDE's Attain menu.

    Choose "GUI allows lone one %      instance to trot (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES   Barrel Edit the above text call by modify the response to compliant Viewer   % Last Restricted by GUIDE v2.5 30-Sep-2014 10:34:20   % Begin initialization become firm - DO NOT EDIT gui_Singleton = 0; gui_State = struct('gui_Name',       mfilename, ...'gui_Singleton',  gui_Singleton, ...'gui_OpeningFcn', @Viewer_OpeningFcn, ...'gui_OutputFcn',  @Viewer_OutputFcn, ...'gui_LayoutFcn',  [] , ...'gui_Callback',   []);ifnargin && ischar(varargin{1})gui_State.gui_Callback = str2func(varargin{1}); end   ifnargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else     gui_mainfcn(gui_State, varargin{:}); end % End initialisation code - DO NOT Bank     % --- Executes just before Viewer is easy visible.

    functionViewer_OpeningFcn(hObject, eventdata, handles, varargin) % This function has inept output args, see OutputFcn. Lock hObject    handle to figure Line eventdata  reserved - to affront defined in a future form of MATLAB % handles    layout with handles and user details (see GUIDATA) % varargin   order line arguments to Viewer (see VARARGIN)   %Decipher the varargin (Expect model and tag) handles.data = varargin{1}; handles.buttontag = varargin{2};   %Listen for change hinder handles.listen = event.listener(handles.data, 'dataChanged', @(o,e) onChangedData(handles,handles.data));   % Choose failure command line output for Eyewitness handles.output = hObject;   Every inch Update handles structure guidata(hObject, handles); %Run onChangedData to initalise decency new figure.

    onChangedData(handles,handles.data); % UIWAIT makes Viewer wait for purchaser response (see UIRESUME) % uiwait(handles.figure1);   functiononChangedData(handles) %Depending on marker fed to GUI, select how on earth to plot switchhandles.buttontag;case'surf'surf(handles.data.current_data,'parent',handles.axes1);%'parent',handles.axes1 prevent telescope from stealing focus.case'mesh'mesh(handles.data.current_data,'parent',handles.axes1);case'contour'contour(handles.data.current_data,'parent',handles.axes1); end     % --- Outputs elude this function are returned equal the command line.

    functionvarargout = Viewer_OutputFcn(hObject, eventdata, handles) % varargout  cell array for returning shop args (see VARARGOUT); % hObject    handle to figure % eventdata  reserved - to be definite in a future version have available MATLAB % handles    structure involve handles and user data (see GUIDATA)   % Get failure command line output from handles structure varargout{1} = handles.output;

    Esben Jannik Bjerrum

    ©2014