External Interfaces/API |
Examples of MATLAB as an Automation Client
This section provides examples of using MATLAB as an Automation client with controls and servers.
MATLAB ships with a very simple example COM control that draws a circle on the screen, displays some text, and fires events when the user single- or double-clicks on the control. Create the control by running the mwsamp.m
file in the directory, winfun\comcli
, or type
This control is stored in the MATLAB bin
, or executable, directory along with the control's type library. The type library is a binary file used by COM tools to decipher the control's capabilities. See the section Writing Event Handlers for other examples that use the mwsamp
controls.
Using MATLAB as an Automation Client
This example uses MATLAB as an Automation client and Microsoft Excel as the server. It provides a good overview of typical functions. In addition, it is a good example of using the Automation interface of another application:
% MATLAB Automation client example % % Open Excel, add workbook, change active worksheet, % get/put array, save. % First, open an Excel Server. e = actxserver('excel.application'); % Insert a new workbook. eWorkbooks = get(e, 'Workbooks'); eWorkbook = Add(eWorkbooks); set(e, 'Visible', 1); % Make the second sheet active. eActiveWorkbook = get(e, 'ActiveWorkBook'); eSheets = get(eActiveWorkbook, 'Sheets'); eSheet2 = Item(eSheets, 2); Activate(eSheet2); % Get a handle to the active sheet. eActiveSheet = get(e, 'ActiveSheet'); % Put a MATLAB array into Excel. A = [1 2; 3 4]; eActiveSheetRange = Range(eActiveSheet, 'A1', 'B2'); set(eActiveSheetRange, 'Value', A); % Get back a range. It will be a cell array, since the cell range % can contain different types of data. eRange = Range(eActiveSheet, 'A1', 'B2'); B = get(eRange, 'Value'); % Convert to a double matrix. The cell array must contain only % scalars. B = reshape([B{:}], size(B)); % Now, save the workbook. SaveAs(eWorkbook, 'myfile.xls'); % To avoid saving the workbook and being prompted to do so, % uncomment the following code. % set(eWorkbook, 'Saved', 1); % Close(eWorkbook); % Quit Excel and delete the server. % Quit(e); % delete(e);
Note Make sure that you always close any workbooks that you add in Excel. This can prevent potential memory leaks. |
Writing Event Handlers | Additional COM Client Information |