| Contents | Index |
| On this page… |
|---|
Overview of MATLAB COM Client Examples Example — Using Internet Explorer Program in a MATLAB Figure |
A COM client is a program that manipulates COM objects. These objects can run in the MATLAB application or can be part of another application that exposes its objects as a programmatic interface to the application.
This section provides examples that show how to use MATLAB as a COM client.
Note You can also access MATLAB as an Automation server from other applications, such as those written in the Microsoft Visual Basic programming language. For information on this technique, see Calling MATLAB COM Automation Server. |
To start using COM objects, you need to create the object and get information about it. This section covers the following topics:
Two MATLAB functions enable you to create COM objects:
actxcontrol — Creates an instance of a control in a MATLAB figure.
actxserver — Creates and manipulates objects from MATLAB that are exposed in an application that supports Automation.
Each function returns a handle to the object's main interface, which you use to access the object's methods, properties, and events, and any other interfaces it provides.
In general, you can determine what you can do with an object using the methods, get, and events functions.
Information about Methods. To list the methods supported by the object handle, type:
handle.methods
Information about Properties. To list the properties of the object handle, type:
get(handle)
To see the value of the property PropertyName, type:
get(handle,'PropertyName')
Use set to change a property value.
Information about Events. To list the events supported by the object handle, type:
handle.events
For more information on calling syntax, see Getting Interfaces to the Object and Invoking Methods on an Object. For more information on events, see Using Events.
To get the programmatic identifier (ProgID) of a COM control that is already registered on your computer, use the actxcontrollist command. You can also use the ActiveX Control Selector, displayed with the command actxcontrolselect. This interface lets you see instances of the controls installed on your computer.
For more information on using these commands, see Creating an ActiveX Control.
If your MATLAB program uses a custom control (e.g., one that you have created especially for your application), you must register it with the Microsoft Windows operating system before you can use it. You can do this from your MATLAB program by issuing an operating system command:
!regsvr32 /s filename.ocx
where filename is the name of the file containing the control. Using this command in your program enables you to provide custom-made controls that you make available to other users by registering the control on their computer when they run your MATLAB program. You might also want to supply versions of a Microsoft ActiveX control to ensure that all users have the same version.
For more information about registration, see Registering Controls and Servers.
The following examples illustrate various techniques for using MATLAB software as a COM client. Some of the examples use ActiveX controls, which is a specific type of COM object. For a description, see COM Objects, Clients, and Servers.
Example — Using Internet Explorer Program in a MATLAB Figure — This example uses the ActiveX control exposed by Internet Explorer web browser to add an HTML viewer to a MATLAB Figure, which also contains an axes object for plotting. As the user clicks various graphics objects that are displayed in the figure (including the figure itself), the documentation of the object's properties is displayed in the viewer.
Example — Grid ActiveX Control in a Figure — This example puts a spreadsheet-like grid control in a figure and uses the control's mouse-down event to trigger the acquisition of data from the grid and plot the data in the axes.
Example — Reading Excel Spreadsheet Data — This MATLAB GUI reads data programmatically from an Excel spreadsheet. By running an Automation server, the MATLAB software can access the objects exposed by the spreadsheet program, which provides a variety of interfaces to the application.
This example uses the ActiveX control Shell.Explorer, which is exposed by the Microsoft Internet Explorer application, to include an HTML viewer in a MATLAB figure. The figure's window button down function is then used to select a graphics object when the user clicks the graph and load the object's property documentation into the HTML viewer.
Using Internet Explorer from an ActiveX client program.
Defining a window button down function that displays HTML property documentation for whatever object the user clicks.
Defining a resize function for the figure that also resizes the ActiveX object container.
This example creates a larger than normal figure window that contains an axes object and an HTML viewer on the lower part of the figure window. By default, the viewer displays the URL http://www.mathworks.com. When you issue a plotting command, such as:
surfc(peaks(20))
the graph displays in the axes.
Click anywhere in the graph to see the property documentation for the selected object.

You can open the file that implements this example in MATLAB Editor or you can run this example with the following links:
This example defines the figure size based on the default figure size and adds space for the ActiveX control. Here is the code to define the figure:
dfpos = get(0,'DefaultFigurePosition');
hfig = figure('Position',dfpos([1 2 3 4]).*[.8 .2 1 1.65],...
'Menu','none','Name','Create a plot and click on an object',...
'ResizeFcn',@reSize,...
'WindowButtonDownFcn',@wbdf,...
'Renderer','Opengl',...
'DeleteFcn',@figDelete);Note that the figure also defines a resize function and a window button down function by assigning function handles to the ResizeFcn and WindowButtonDownFcn properties. The callback functions reSize and wbdf are defined as nested functions in the same file.
The figure's delete function (called when the figure is closed) provides a mechanism to delete the control.
The actxcontrol function creates the ActiveX control inside the specified figure and returns the control's handle. You need to supply the following information:
Control's programmatic identifier (use actxcontrollist to find it)
Location and size of the control container in the figure (pixels) [left bottom width height]
Handle of the figure that contains the control:
conSize = calcSize; % Calculate the container size
hExp = actxcontrol('Shell.Explorer.2',conSize,hfig); % Create the control
Navigate(hExp,'http://www.mathworks.com/'); % Specify content of html viewerThe nested function, calcSize calculates the size of the object container based on the current size of the figure. calcSize is also used by the figure resize function, which is described in the next section.
function conSize = calcSize fp = get(hfig,'Position'); % Get current figure size conSize = [0 0 1 .45].*fp([3 4 3 4]); % Calculate container size end % calcSize
In MATLAB, you can change the size of a figure and the axes automatically resize to fit the new size. This example implements similar resizing behavior for the ActiveX object container within the figure using the object's move method. This method enables you to change both size and location of the ActiveX object container (i.e., it is equivalent to setting the figure Position property).
When you resize the figure window, the MATLAB software automatically calls the function assigned to the figure's ResizeFcn property. This example implements the nested function reSize for the figure reSize function.
ResizeFcn at Figure Creation. The resize function first determines if the ActiveX object exists because the MATLAB software calls the figure resize function when the figure is first created. Since the ActiveX object has not been created at this point, the resize function simply returns.
When the Figure Is Resized. When you change the size of the figure, the resize function executes and does the following:
Calls the calcSize function to calculate a new size for the control container based on the new figure size.
Calls the control's move method to apply the new size to the control.
function reSize(src,evnt)
if ~exist('hExp','var')
return
end
conSize = calcSize;
move(hExp,conSize);
end % reSizeThis example uses the figure WindowButtonDownFcn property to define a callback function that handles mouse click events within the figure. When you click the left mouse button while the cursor is over the figure, the MATLAB software executes the WindowButtonDownFcn callback on the mouse down event.
The callback determines which object was clicked by querying the figure CurrentObject property, which contains the handle of the graphics object most recently clicked. Once you have the object's handle, you can determine its type and then load the appropriate HTML page into the Shell.Explorer control.
The nested function wbdf implements the callback. Once it determines the type of the selected object, it uses the control Navigate method to display the documentation for the object type.
function wbdf(src,evnt)
cobj = get(hfig,'CurrentObject');
if isempty(cobj)
disp('Click somewhere else')
return
end
pth = 'http://www.mathworks.com/help/techdoc/ref/';
typ = get(cobj,'Type');
switch typ
case ('figure')
Navigate(hExp,[pth,'figure_props.html']);
case ('axes')
Navigate(hExp,[pth,'axes_props.html']);
case ('line')
Navigate(hExp,[pth,'line_props.html']);
case ('image')
Navigate(hExp,[pth,'image_props.html']);
case ('patch')
Navigate(hExp,[pth,'patch_props.html']);
case ('surface')
Navigate(hExp,[pth,'surface_props.html']);
case ('text')
Navigate(hExp,[pth,'text_props.html']);
case ('hggroup')
Navigate(hExp,[pth,'hggroupproperties.html']);
otherwise % Display property browser
Navigate(hExp,[pth(1:end-4),'infotool/hgprop/doc_frame.html']);
end
end % wbdfThis example uses the figure delete function (DeleteFcn property) to delete the ActiveX object before closing the figure. The MATLAB software calls the figure delete function before deleting the figure, which enables the function to perform any clean up needed before closing the figure. The figure delete function calls the control's delete method.
function figDelete(src,evnt) hExp.delete; end
This example adds a Microsoft ActiveX spreadsheet control to a figure, which also contains an axes object for plotting the data displayed by the control. Clicking a column in the spreadsheet causes the data in that column to be plotted. Clicking down and dragging the mouse across multiple columns plots all columns touched.
Registering a control for use on your system.
Writing a handler for one of the control's events and using the event to execute MATLAB plotting commands.
Writing a resize function for the figure that manages the control's size as users resize the figure.
This example assumes that your data samples are organized in columns and that the first cell in each column is a title, which is used by the legend. See Complete Code Listing for an example of how to load data into the control.
Once the data is loaded, click the column to plot the data. The following picture shows a graph of the results of Test2 and Test3 created by selecting column B and dragging and releasing on column C.

You can open the file used to implement this example in MATLAB Editor:
The ActiveX control used in this example is typical of those downloadable from the Internet. Once you have downloaded the files you need, register the control on your system using the DOS command regsvr32. In a command prompt, enter a command of the following form:
regsvr32 sgrid.ocx
From the MATLAB command line, type:
system 'regsvr32 sgrid.ocx'
See the section Registering Controls and Servers for more information.
Finding the Control's ProgID. Once you have installed and registered the control, you can obtain its programmatic identifier using the ActiveX Control Selector dialog. To display this dialog box, use the actxcontrolselect command. Locate the control in the list and the selector displays the control and the ProgID.

This example creates a figure that contains an axes object and the grid control. The first step is to determine the size of the figure and then create the figure and axes. This example uses the default figure and axes size (obtained from the respective Position properties) to calculate a new size and location for each object.
dfpos = get(0,'DefaultFigurePosition');
dapos = get(0,'DefaultAxesPosition');
hfig = figure('Position',dfpos([1 2 3 4]).*[1 .8 1 1.25],...
'Name','Select the columns to plot',...
'Renderer','ZBuffer',...
'ResizeFcn',{@reSize dfpos(3)});
hax = axes('Position',dapos([1 2 3 4]).*[1 4 1 .65]);The above code moves the figure down from the top of the screen (multiply second element in position vector by .8) and increases the height of the figure (multiply fourth element in position vector by 1.25). Axes are created and sized in a similar way.
Use the actxcontrol function to create an instance of the control in a figure window. This function creates a container for the control and enables you to specify the size of this container, which usually defines the size of the control. See Managing Figure Resize for a specific example.
Specifying the Size and Location. The control size and location in the figure is calculated by a nested function calcSize. This function is used to calculate both the initial size of the control container and the size resulting from resize of the figure. It gets the figure's current position (i.e., size and location) and scales the four-element vector so that the control container is
Positioned at the lower-left corner of the figure.
Equal to the figure in width.
Has a height that is .35 times the figure's height.
The value returned is of the correct form to be passed to the actxcontrol function and the control's move method.
function conSize = calcSize fp = get(hfig,'Position'); conSize = fp([3 4 3 4]).*[0 0 1 .35]; end % conSize
Creating the Control. Creating the control entails the following steps:
Calculating the container size
Instantiating the control in the figure
Setting the number of rows and columns to match the size of the data array
Specifying the width of the columns
conSize = calcSize;
hgrid = actxcontrol('SGRID.SgCtrl.1',conSize,hfig);
hgrid.NRows = size(dat,1);
hgrid.NColumns = size(dat,2);
colwth = 4350; hdwth = hgrid.HdrWidth;
SetColWidth(hgrid,0,sz(2)-1,colwth,1)This example uses the control's Click event to implement interactive plotting. When a user clicks the control, the MATLAB software executes a function that plots the data in the column where the mouse click occurred. Users can also select multiple columns by clicking down and dragging the cursor over more than one column.
Registering the Event. You need to register events with MATLAB so that when the event occurs (a mouse click in this case), the MATLAB software responds by executing the event handler function. Register the event with the registerevent function:
hgrid.registerevent({'Click',@click_event});Pass the event name (Click) and a function handle for the event handler function inside a cell array.
Defining the Event Handler. The event handler function click_event uses the control's GetSelection method to determine what columns and rows have been selected by the mouse click. This function plots the data in the selected columns as lines, one line per column.
It is possible to click down on a column and drag the mouse to select multiple columns before releasing the mouse. In this case, each column is plotted because the event is not fired until the mouse button is released (which reflects the way the author chose to implement the control). The legend function uses the column number stored in the variable cols to label the individual plotted lines. You must add one to cols because the control counts the columns starting from zero.
Note that you implement event handlers to accept a variable number of arguments (varargin).
function click_event(varargin)
[row1,col1,row2,col2] = hgrid.GetSelection(1,1,1,1,1);
ncols = (col2-col1)+1;
cols = [col1:col2];
for n = 1:ncols
hgrid.Col = cols(n);
for ii = 1:sz(1)
hgrid.Row = ii;
plot_data(ii,n) = hgrid.Number;
end
end
hgrid.SetSelection(row1,col1,row2,col2);
plot(plot_data)
legend(labels(cols+1))
end % click_eventThe size and location of a MATLAB axes object is defined in units that are normalized to the figure that contains it. Therefore, when you resize the figure, the axes automatically resize proportionally. When a figure contains objects that are not contained in axes, you are responsible for defining a function that manages the resizing process.
The figure ResizeFcn property references a function that executes whenever the figure is resized and also when the figure is first created. This example creates a resize function that manages resizing grid control by doing the following:
Disables control updates while changes are being made to improve performance (use the hDisplay property).
Calculates a new size for the control container based on the new figure size (calcSize function).
Applies the new size to the control container using its move method.
Scales the column widths of the grid proportional to the change in width of the figure (SetColWidth method).
Refreshes the display of the control, showing the new size.
function reSize(src,evnt,dfp)
% Return if control does not exist (figure creation)
if ~exist('hgrid','var')
return
end
% Resize container
hgrid.bDisplay = 0;
conSize = calcSize;
move(hgrid,conSize);
% Resize columns
scl = conSize(3)/dfp;
ncolwth = scl*colwth;
nhdrwth = hdwth*(scl);
hgrid.HdrWidth = nhdrwth;
SetColWidth(hgrid,0,sz(2)-1,ncolwth,2)
hgrid.Refresh;
end % reSizeThis example uses the figure delete function (DeleteFcn property) to delete the ActiveX object before closing the figure. The MATLAB software calls the figure delete function before deleting the figure, which enables the function to perform any clean up needed before closing the figure. The figure delete function calls the control's delete method.
function figDelete(src,evnt) hgrid.delete; end
This example creates a graphical interface to access the data in a Microsoft Excel file. To enable the communication between the MATLAB software and the spreadsheet program, this example creates an Microsoft ActiveX object in an Automation server running an Excel application. The MATLAB software then accesses the data in the spreadsheet through the interfaces provided by the Excel Automation server.
This example shows how to use the following techniques:
Use of an Automation server to access another application from the MATLAB software.
Ways to manipulate Excel data into types used in the GUI and plotting.
Implementing a GUI that enables plotting of selected columns of the Excel spreadsheet.
Inserting a MATLAB figure into an Excel file.
To use the GUI, select any items in the list box and click the Create Plot button. The sample data provided with this example contain three input and three associated response data sets, all of which are plotted versus the first column in the Excel file, which is the time data.
You can view the Excel data file by clicking the Show Excel Data File button, and you can save an image of the graph in a different Excel file by clicking Save Graph button. Note that the Save Graph option creates a temporary PNG file in your working folder.
The following picture shows the GUI with an input/response pair selected in the list box and plotted in the axes.

You can open the file used to implement this example in MATLAB Editor or run this example:
This example assumes a particular organization of the Excel spreadsheet, as shown in the following picture.

The format of the Excel file is as follows:
The first element in each column is a text string that identifies the data contain in the column. These strings are extracted and used to populate the list box.
The first column (Time) is used for the x-axis of all plots of the remaining data.
All rows in each column are read into the MATLAB software.
The first step in accessing the spreadsheet data from the MATLAB software is to run the Excel application in an Automation server process using the actxserver function and the program ID, excel.application.
exl = actxserver('excel.application');The ActiveX object that is returned provides access to a number of interfaces supported by the Excel program. Use the workbook interface to open the Excel file containing the data.
exlWkbk = exl.Workbooks; exlFile = exlWkbk.Open([docroot '/techdoc/matlab_external/examples/input_resp_data.xls']);
Use the workbook's sheet interface to access the data from a range object, which stores a reference to a range of data from the specified sheet. This example accesses all the data in column A, first cell to column G, last cell:
exlSheet1 = exlFile.Sheets.Item('Sheet1');
robj = exlSheet1.Columns.End(4); % Find the end of the column
numrows = robj.row; % And determine what row it is
dat_range = ['A1:G' num2str(numrows)]; % Read to the last row
rngObj = exlSheet1.Range(dat_range);At this point, the entire data set from the Excel file's sheet1 is accessed via the range object interface. This object returns the data in a MATLAB cell array, which can contain both numeric and character data:
exlData = rngObj.Value;
Now that the data is in a cell array, you can use MATLAB functions to extract and reshape parts of the data into the forms needed to use in the GUI and pass to the plot function.
The following code performs two operations:
Extracts numeric data from the cell array (indexing with curly braces), concatenates the individual doubles returned by the indexing operation (square brackets), and reshapes it into an array that arranges the data in columns.
Extracts the string in the first cell in each column of an Excel sheet and stores them in a cell array, which is used to generate the items in the list box.
for ii = 1:size(exlData,2)
matData(:,ii) = reshape([exlData{2:end,ii}],size(exlData(2:end,ii)));
lBoxList{ii} = [exlData{1,ii}];
endThis example uses a GUI that enables you to select from a list of input and response data from a list box. All data is plotted as a function of time (which is, therefore, not a choice in the list box) and you can continue to add more data to the graph. Each data plot added to the graph causes the legend to expand.
Additional implementation details include:
A legend that updates as you add data to a graph
A clear button that enables you to clear all graphs from the axes
A save button that saves the graph as a PNG file and adds it to another Excel file
A toggle button that shows or hides the Excel file being accessed
The figure delete function (DeleteFcn property), which the MATLAB software calls when the figure is closed, is used to terminate the Automation server process.
Selecting and Plotting Data. When you click the Create Plot button, its callback function queries the list box to determine what items are selected and plots each data versus time. The legend is updated to display any new data while maintaining the legend for the existing data.
function plotButtonCallback(src,evnt)
iSelected = get(listBox,'Value');
grid(a,'on');hold all
for p = 1:length(iSelected)
switch iSelected(p)
case 1
plot(a,tme,matData(:,2))
case 2
plot(a,tme,matData(:,3))
case 3
plot(a,tme,matData(:,4))
case 4
plot(a,tme,matData(:,5))
case 5
plot(a,tme,matData(:,6))
case 6
plot(a,tme,matData(:,7))
otherwise
disp('Select data to plot')
end
end
[b,c,g,lbs] = legend([lbs lBoxList(iSelected+1)]);
end % plotButtonCallbackClearing the Axes. The plotter is designed to continually add graphs as the user selects data from the list box. The Clear Graph button clears and resets the axes and clears the variable used to store the labels of the plot data (used by legend).
%% Callback for clear button function clearButtonCallback(src,evt) cla(a,'reset') lbs = ''; end % clearButtonCallback
Display or Hide Excel File. The MATLAB program has access to the properties of the Excel application running in the Automation server. By setting the Visible property to 1 or 0, this callback controls the visibility of the Excel file.
%% Display or hide Excel file function dispButtonCallback(src,evt) exl.visible = get(src,'Value'); end % dispButtonCallback
Close Figure and Terminate Excel Automation Process. Since the Excel Automation server runs in a separate process from the MATLAB software, you must terminate this process explicitly. There is no reason to keep this process running after the GUI has been closed, so this example uses the figure's delete function to terminate the Excel process with the Quit method. Also, terminate the second Excel process used for saving the graph. See Inserting MATLAB Graphs Into Excel Spreadsheets for information on this second process.
%% Terminate Excel processes function deleteFig(src,evt) exlWkbk.Close exlWkbk2.Close exl.Quit exl2.Quit end % deleteFig
You can save the graph created with this GUI in an Excel file. (This example uses a separate Excel Automation server process for this purpose.) The callback for the Save Graph push button creates the image and adds it to an Excel file:
Both the axes and legend are copied to an invisible figure configured to print the graph as you see it on the screen (figure PaperPositionMode property is set to auto).
The print command creates the PNG image.
Use the Shapes interface to insert the image in the Excel workbook.
The server and interfaces are instanced during GUI initialization phase:
exl2 = actxserver('excel.application');
exlWkbk2 = exl2.Workbooks;
wb = invoke(exlWkbk2,'Add');
graphSheet = invoke(wb.Sheets,'Add');
Shapes = graphSheet.Shapes;The following code implements the Save Graph button callback:
function saveButtonCallback(src,evt)
tempfig = figure('Visible','off','PaperPositionMode','auto');
tempfigfile = [tempname '.png'];
ah = findobj(f,'type','axes');
copyobj(ah,tempfig) % Copy both graph axes and legend axes
print(tempfig,'-dpng',tempfigfile);
Shapes.AddPicture(tempfigfile,0,1,50,18,300,235);
exl2.visible = 1;
end
![]() | Introducing MATLAB COM Integration | Supported Client/Server Configurations | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |