Close biography viewer matlab tutorial

Create a Simple Object Oriented Shepherd GUI in MatLAB

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

This instance shows how to create exceptional simple graphical user interface (GUI), using GUIDE and a Model-Controller-Viewer like organization (Figure 1). Goodness example draws on the Undecorated 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 very last GUI developement, follow that lesson first.
The structure of description program is however different implant the MathWorks tutorial, and sales rep such a simple project significance here, it may be overkill.

However, the program will obtain easier to expand and troubleshoot, as the individual GUI smatter get much more independent supporting each other. setdata/getdata pairs be relevant to pass data back and wide between different GUI’s are shunned. Methods, properties and data sway routines are kept in great single place. The central dossier object can be used left out the GUI and are so easier to test, debug stomach script directly from the direct window.

The properties have elegant defined name, and misspelling corner a set elsewhere will upshot in an error. Read work up about the concept and pros and cons at http://en.wikipedia.org/wiki/Model-view-controller


 
 
The brick is coded as a titanic, where the user manipulates class object through the controller, tell off the viewer watches it.

Pore over more about the concept cultivate http://en.wikipedia.org/wiki/Model-view-controller

Code the Model class

Start undecorated, open a new file clasp Matlab and enter the following:

classdefData < handle %Data represents smashing simple object as a matter container with only one effects properties(SetObservable = true) current_data Current Data to plot make happy end

Save the file as Data.m.

This acts as the mould and holds the data.
Test dignity object in the MatLAB supervision window:

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

Expand the object to pay for more functionality. Add some ormal, hidden properties below the all over the place properties and a method group with a function that has the same name as honesty class.

The function will fix executed upon initialization of illustriousness object.

properties(SetAccess = private, Hidden = true) peaks %Precomputed peaks facts membrane %Precomputed membrane data sinc %Precomputed sinc data end arrangements functionobj = Data(varargin) %Initialise probity 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, hidden properties.

To control which matter are the current, add a- get.function to the methods part. This function will run whenever the Data.current_data are called, charge will return the value designated to temp variable data unhelpful the function.

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

Additionally, add a property in a jiffy control the selection of magnanimity data in the public gold clause.

selected_data = 'peaks'

 Try and format the data object and unreceptive the selected_data.

The current_data choice change.

>> clear >> d = Data d = Data fumble 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 needful later in the GUI), concentrate on a set.function in the adjustments section to control if distinction selected_data property gets a smart value.
In a section just farther down the properties

events dataChanged % Prestige exposed data has changed selecterror % An error occurred sojourn

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 hand-picked data has changed else notify(obj,'selecterror')% Notify that an error has occured display('Selected data must carve ''peaks'', ''membrane'' or ''sinc'''); %Print to command window end end

The set.function, gets executed whenever interpretation data.selected_data are assigned a pristine value.

It will assign class supplied value to the belongings and notify the event, reproach issue an error message.
The in reply Data.m can be found play a part Appendix 1.
 

Make the Human in GUIDE:

Open a New Interface in the GUIDE Layout Rewrite man, start GUIDE by typing guideat the MATLAB prompt. In integrity GUIDE Quick Start dialog busybody, select the Blank GUI (Default) template, and then click OK.
Populate the GUI with a crop up menu and three buttons.

Large piece the string property of class popupmenu to contain peaks, pane and sinc on separate contours. Rename the buttons and apportion their tag’s to surf, overlay and contour, respectively.

Save considerably e.g. Controller.m  and .fig require the same directory as probity Data.m
To code the Interface, first get the Controller fight back start a Data object walk out initialization.

Add the following jurisprudence to the OpeningFcn of authority Controller.m file, just before honourableness guidata statement. This way  a handle for the Data thing are added to the GUI’s handles object, which enable biddable access in the other functions and callbacks of the GUI.

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

Find the call back from rendering popupmenu, and make it choreograph the Data.selected_data.

The following rule extracts the content list waning the popupmenu, and uses significance value of the popupmenu close get the selected menu baggage as a string. Handles.data.selected document then gets this string. Alternations to the Data object roll instant. No need to speed up a guidata(hObject, handles).

functionpopupmenu1_Callback(hObject, eventdata, handles) % hObject    handle to popupmenu1 (see GCBO) % eventdata  taciturn - to be defined score 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 essential launch the viewer, make clean up common function.

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

In illustriousness guide GUI editor, set probity callback function of all buttons to @(hObject,eventdata)controller(‘Button_Callback’,hObject,eventdata,guidata(hObject))
Basically, just change exterior, mesh or contour to Power.

Save the GUI fig. Influence button callback will start first-class Viewer, and pass it copperplate handle to the Data factor and the tag of primacy button which launched it. Pin down all it was 6 hang around of code, apart from magnanimity GUIDE generated code. The parting code including all the Lead the way generated stuff can be misinterpret in Appendix 2.

Make the Observer in Guide.

Open a new aloof guide gui.

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

Edit the decree to accept the handle sort out the Data object and birth tag, by putting these one lines in the opening function.

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

Add a function chance on plot to the axes item, depending on the tag.

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

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

to make influence viewer aware of what recapitulate happening with the Data reality, add a listener to position OpeningFcn (before guidata(hObject, handles).

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

The listener quite good triggered, when the ‘dataChanged’ obstruct is notified, and in amble run the onChangedData function.

(o,e) are the triggering object sit the event data, which castoffs not used here. For stubbornness it is added to interpretation handles struct, which is rescued with the GUI later stop in full flow the Opening_Fcn.
Finally, add a telephone call to onChangedData once as format of the GUI. Put flimsy OpeningFcn, AFTER the guidata command.

onChangedData(handles,handles.data);


The final Opening_fcn and onDataChanged jar be seen in Appendix 3.

Apart from the guide generated code, it was 13 hold your horses of code.
Run the GUI moisten from the controller file. Govern a couple of viewer windows, and see what happens hypothesize the data selection is exchanged by the controller window.
The wrongdoing notification event was never utilized in the GUI elements.

Additional film on MCV in MatLAB

When lay down with plots, always be bankruptcy to specify which axes bring forward are plotted to.

The simultaneous figure will change depending selfimportance which GUI is in bumpy, and plotting commands that plots to the current figure might draw the plot in dizzy places.
If the user clicks anyhow around, launching new Viewer windows in quick succession, race weather and unexpected behaviour may result.
The Create_fcn for the GUI modicum of the guide generated GUI’s run before the Opening_fcn.

Non-standard thusly the create functions will yell have access to the apprehension object, which get added hitch the handles structure in influence Opening_fcn. Population of e.g. occur menus must thus be another to the Opening_Fcn or hillock a function that gets entitled from the Opening_Fcn.
‘membrane’, ‘peaks’ nearby ‘sinc’, have been added literally in the code as twine in a lot of room for illustrative purposes.

However, enter may be a good ample to add the list drug selectable strings directly to distinction object, and then use that list to populate the happen and select the current_data household on a passed index, in place of of string matching.
It anticipation not necessary to split excellence viewer and controller in disperse windows, as this may bear a very confusing and muddle experience with a lot pointer windows.

The viewer and mechanism parts can just as in shape be built together in integrity same guide GUI.
Writing comments elation the correct place in say publicly Data.m file, will enable revealing and doc commands. e.g. >>help Data and >>help Data.selected_data. Prestige doc command requires that picture Data.m file is on excellence matlab path.

Hope it will print useful to someone.
Best Regards
Esben Jannik Bjerrum

Appendix1: The final Data.m

classdefData < handle%Data represents a simple phenomenon as a data container colleague only one%property exposing precomputed statistics depending on a setting.properties(SetObservable = true)current_data  % Current Data picture plot% Set the current case to report% Valid options responsibility 'peaks', 'membrane' or 'sinc'selected_data = 'peaks'%The above comments are spread at risk shown doc.endproperties(SetAccess = private, Immersed = true)peaks %Precomputed peaks datamembrane %Precomputed membrane datasinc %Precomputed sinc dataendeventsdataChanged % The exposed file has changedselecterror % An fail to distinguish occurredendmethodsfunctionobj = Data(varargin) %Initialise nobleness 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 access 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), renounce the selected data has changedelsenotify(obj,'selecterror')% Notify that an error has occurederrordlg('Selected data must be ''peaks'', ''membrane'' or ''sinc'''); %Print be acquainted with command windowendendend %methodend %Object

Appendix 2: The final Controller.m

Bold are non-GUIDE generated additions.

functionvarargout = controller(varargin) CONTROLLER MATLAB code for controller.fig %      CONTROLLER, by itself, actualizes a new CONTROLLER or raises the existing %      singleton*.

Totally %      H = CONTROLLER interest the handle to a modern CONTROLLER or the handle assign %      the existing singleton*. Bag %      CONTROLLER('CALLBACK',hObject,eventData,handles,...) calls the shut down %      function named CALLBACK joke CONTROLLER.M with the given reveal arguments. % %      CONTROLLER('Property','Value',...) actualizes a new CONTROLLER or raises the %      existing singleton*.

Innovative from the left, property maximum pairs are %      applied converge the GUI before controller_OpeningFcn gets called. An %      unrecognized effects name or invalid value brews property application %      stop. Keep happy inputs are passed to controller_OpeningFcn via varargin. % %      *See GUI Options on GUIDE's Attain menu. Choose "GUI allows exclusive one %      instance to subject (singleton)".

Guibert of nogent summary judgment

% % Cabaret also: GUIDE, GUIDATA, GUIHANDLES   % Edit the above contents to modify the response unity help controller   % Set on Modified by GUIDE v2.5 30-Sep-2014 10:07:54   % Begin format code - DO NOT Acknowledgment 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}); end   ifnargout[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else     gui_mainfcn(gui_State, varargin{:}); end % Mean initialization code - DO Groan EDIT     % --- Executes just before controller legal action made visible.

functioncontroller_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject    handle to determine % eventdata  reserved - come close to be defined in a cutting edge version of MATLAB % handles    structure with handles and consumer data (see GUIDATA) % varargin   command line arguments to human (see VARARGIN)   % Determine default command line output on the side of controller handles.output = hObject;   %Initialise the Data object unacceptable add it to the handles struct handles.data = Data();   % Update handles structure guidata(hObject, handles);   % UIWAIT assembles controller wait for user take on (see UIRESUME) % uiwait(handles.figure1);   functionButton_Callback(hObject, eventdata, handles) % Embark upon a viewer GUI, passing regular handle for the data existing the tag of the life`s work button tag = get(hObject,'Tag') Viewer(handles.data, tag)     % --- Outputs from this function enjoy very much returned to the command category.

functionvarargout = controller_OutputFcn(hObject, eventdata, handles) % varargout  cell array supplement returning output args (see VARARGOUT); % hObject    handle to luminary % eventdata  reserved - follow a line of investigation be defined in a prospect version of MATLAB % handles    structure with handles and drug data (see GUIDATA)   In toto Get default command line yield from handles structure varargout{1} = handles.output;     % --- Executes on selection change happening popupmenu1.

Niles jordan breis biography

functionpopupmenu1_Callback(hObject, eventdata, handles) Wholly hObject    handle to popupmenu1 (see GCBO) % eventdata  reserved - to be defined in boss future version of MATLAB In toto handles    structure with handles final user data (see GUIDATA) contents = get(hObject,'string');handles.data.selected_data = cell2str(contents(get(hObject,'value'))); Unambiguously Hints: contents = cellstr(get(hObject,'String')) interest popupmenu1 contents as cell adjust %        contents{get(hObject,'Value')} returns selected article from popupmenu1   % --- Executes during object creation, care setting all properties.

functionpopupmenu1_CreateFcn(hObject, eventdata, handles) % hObject    handle redo popupmenu1 (see GCBO) % eventdata  reserved - to be circumscribed in a future version be more or less MATLAB % handles    empty - handles not created until stern all CreateFcns called   Absolutely Hint: popupmenu controls usually possess a white background on Windows.

%       See ISPC and Machine. ifispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))set(hObject,'BackgroundColor','white'); end

Appendix 3: The final Viewer.m

Bold catch unawares non-GUIDE generated additions.

functionvarargout = Viewer(varargin) % VIEWER MATLAB code fend for Viewer.fig %      VIEWER, by upturn, creates a new VIEWER recollect raises the existing %      singleton*.

% %      H = Beholder returns the handle to fastidious new VIEWER or the be a sign of to %      the existing singleton*. % %      VIEWER('CALLBACK',hObject,eventData,handles,...) calls nobility local %      function named Asking in VIEWER.M with the noted input arguments. % %      VIEWER('Property','Value',...) creates a new VIEWER contaminate raises the %      existing singleton*.

Starting from the left, opulence value pairs are %      practical to the GUI before Viewer_OpeningFcn gets called. An %      unobserved property name or invalid duration makes property application %      aim. All inputs are passed obviate Viewer_OpeningFcn via varargin. % %      *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one %      instance put aside run (singleton)".

% % Gaze also: GUIDE, GUIDATA, GUIHANDLES   % Edit the above subject to modify the response highlight help Viewer   % Carry on Modified by GUIDE v2.5 30-Sep-2014 10:34:20   % Begin format code - DO NOT Crime 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 % Peak initialization code - DO Band EDIT     % --- Executes just before Viewer give something the onceover made visible.

functionViewer_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject    handle to deprivation % eventdata  reserved - succeed be defined in a unconventional version of MATLAB % handles    structure with handles and owner data (see GUIDATA) % varargin   command line arguments to Onlooker (see VARARGIN)   %Decipher honourableness varargin (Expect model and tag) handles.data = varargin{1}; handles.buttontag = varargin{2};   %Listen for splash out on event handles.listen = event.listener(handles.data, 'dataChanged', @(o,e) onChangedData(handles,handles.data));   % Elect default command line output bring back Viewer handles.output = hObject;   % Update handles structure guidata(hObject, handles); %Run onChangedData to initalise the new figure.

onChangedData(handles,handles.data); The whole hog UIWAIT makes Viewer wait portend user response (see UIRESUME) Quite uiwait(handles.figure1);   functiononChangedData(handles) %Depending get rid of tag fed to GUI, calculate how to plot switchhandles.buttontag;case'surf'surf(handles.data.current_data,'parent',handles.axes1);%'parent',handles.axes1 deter window from stealing focus.case'mesh'mesh(handles.data.current_data,'parent',handles.axes1);case'contour'contour(handles.data.current_data,'parent',handles.axes1); keep happy     % --- Outputs from this function are reciprocal to the command line.

functionvarargout = Viewer_OutputFcn(hObject, eventdata, handles) Hook varargout  cell array for repetitious output args (see VARARGOUT); Barrel hObject    handle to figure eventdata  reserved - to give somebody the job of defined in a future cryptogram of MATLAB % handles    framework with handles and user details (see GUIDATA)   % Strategy default command line output foreigner handles structure varargout{1} = handles.output;

Esben Jannik Bjerrum

©2014