| Contents | Index |
| On this page… |
|---|
This example shows how to encapsulate MATLAB utilities that perform basic matrix arithmetic. It includes MATLAB code that performs matrix addition, subtraction, multiplication, division and left division and a function to evaluate the eigen values for a matrix. The example shows how to create the COM component using the MATLAB Builder NE product and how to use the COM component in a Microsoft Visual Basic application independent of the MATLAB product.
Note This example assumes that you have downloaded the MATLAB code from http://www.mathworks.com/matlabcentral/ to your work folder. To get the download, search the File Exchange at matlabcentral for MatrixArith. |
At the MATLAB command prompt, change folders to the MatrixMath folder in your work folder.
Enter the command deploytool to open the Deployment Tool window.
Create a project with the following settings:
| Setting | Value |
|---|---|
| Project name | matrixMath |
| Class name | matrixMathclass |
| Project folder | The name of your work folder followed by the project name |
| Generate Verbose Output | Selected |
Locate your work folder and navigate to the matrixMath folder, which contains the MATLAB files needed for the component.
Add the following files to the project:
Build the component by clicking the
button in the Deployment
Tool toolbar.
The build process begins, and a log of the build appears in the Output pane of the Deployment Tool. The files that are needed for the component are copied to two newly created folders, src and distrib, in the matrixMath folder. A copy of the build log is placed in the src folder.
You can call the component from any application that supports COM. Follow these steps to create a Microsoft Visual Basic project and add references to the necessary libraries.
Select Project > References.
Ensure that the following libraries are in the project:
MatrixMath 1.0 Type Library
MWComUtil 7.5 Type Library
Note If you do not see these libraries, you may not have registered the libraries using mwregsvr. Refer to Component Registration for information on this. |
The next step creates a front end or a Microsoft Visual Basic form for the application. End users enter data in this form.
To create a new user form and populate it with the necessary controls:
Make sure that Microsoft Windows Common Controls 6.0 is selected. You will use the Spreadsheet control from this component library.
Add a series of controls to the blank form to create an interface as shown in the next figure.

One of the main components used in the Visual Basic form is a Spreadsheet component. For each Spreadsheet component, set properties as follows.
| Property | Original Value | New Value |
|---|---|---|
DisplayColumnHeaders | True | False |
DisplayHorizontalScrollBar | True | False |
DisplayRowHeaders | True | False |
DisplayTitleBar | True | False |
DisplayToolBar | True | False |
DisplayVerticalScrollBar | True | False |
MaximumWidth | 80% | 100% |
ViewableRange | 1:65536 | A1:E5 |
A consolidated list of components added to the form and the properties modified is as follows.
| Control Type | Control Name | Properties | Purpose |
|---|---|---|---|
Form | frmMatrixMath | Caption = Matrix Laboratory | Container for all components |
Frame | frmInput | Caption = Input Data Points | Groups all input controls |
Frame | frmOutput | Caption = Output Coefficients | Groups all output controls |
Spreadsheet | sheetMat1 | Refer to previous table. | Accepts input matrix 1 from user |
Spreadsheet | sheetMat2 | Refer to previous table. | Accepts input matrix 2 from user |
Spreadsheet | sheetMat3 | Refer to previous table. | Accepts input matrix 3 from user |
Spreadsheet | sheetResultMat | Refer to previous table. | Displays result matrix |
Label | lblAdd | Caption = Add | Labels Add option button |
OptionButton | optOperation | Index = 0 | Option button to perform addition |
Label | lblSub | Caption = Subtract | Labels Subtract option button |
OptionButton | optOperation | Index = 1 | Option button to perform subtraction |
Label | lblMult | Caption = Multiply | Labels Multiply option button |
OptionButton | optOperation | Index = 2 | Option button to perform multiplication |
Label | lblDivide | Caption = Divide | Labels Divide option button |
OptionButton | optOperation | Index = 3 | Option button to perform division |
Label | lblLeftDivide | Caption = Left Divide | Labels Left Divide option button |
OptionButton | optOperation | Index = 4 | Option button to perform left division |
Label | lblEig | Caption = Eigenvalue | Labels Eigenvalue option button |
OptionButton | optOperation | Index = 5 | Option button to calculate Eigenvalue of first matrix |
CommandButton | cmdEvaluate | Caption = Evaluate Default = True | Executes function |
CommandButton | cmdCancel | Caption = Cancel Cancel = True | Closes dialog box without executing function |
When the design is complete, save the project by selecting File > Save. When prompted for the project name, type MatrixMathVB.vbp, and for the form, type frmMatrixMath.frm.
To write the underlying code, right-click frmMatrixMath in the Project window, and select View Code.
The following code listing shows the code to implement. Note that this code references the control and variable names listed above. If you have given a different name to any of the controls or any global variable, change this code to reflect the differences.
Dim theMatCal As matrixMath.matrixMath
Private Sub Form_Initialize()
' Create an instance of the COM object and set the MWArray flags.
' If this fails, exit from the form.
On Error GoTo exit_form
' Create the object.
Set theMatCal = New matrixMath.matrixMath
' Force the input to be of type double.
theMatCal.MWFlags.DataConversionFlags.CoerceNumericToType = mwTypeDouble
' Set the AutoResizeOutput flag to True, so that you do not have to specify
' the size of the output variable as returned by the COM object.
theMatCal.MWFlags.ArrayFormatFlags.AutoResizeOutput = True
' Get the results in a Matrix format.
theMatCal.MWFlags.ArrayFormatFlags.OutputArrayFormat =_
mwArrayFormatMatrix
Exit Sub
exit_form:
' Error handling routine. Since no object is created, display error '
'message and unload the form.
MsgBox ("Error: " & Err.Description)
Unload Me
End Sub
Private Sub Form_Load()
' Set the run time properties for all the components.
frmInputs.TabIndex = 1
sheetMat1.AutoFit = True
' Set the tab order for each component and the viewable range.
' If you need a larger viewable range, you might want to turn the
' horizontal and vertical scroll bars to TRUE.
sheetMat1.TabStop = True
sheetMat1.TabIndex = 1
sheetMat1.Width = 4875
sheetMat1.ViewableRange = "A1:E5"
sheetMat2.TabStop = True
sheetMat2.TabIndex = 2
sheetMat2.Width = 4875
sheetMat2.ViewableRange = "A1:E5"
sheetMat3.TabStop = True
sheetMat3.TabIndex = 3
sheetMat3.Width = 4875
sheetMat3.ViewableRange = "A1:E5"
sheetResultMatTabStop = False
sheetResultMatTabIndex = 1
sheetResultMatWidth = 4875
sheetResultMat.ViewableRange = "A1:E5"
frmOutput.TabIndex = 2
optOperation(0).TabIndex = 3
optOperation(1).TabIndex = 4
optOperation(2).TabIndex = 5
optOperation(3).TabIndex = 6
optOperation(4).TabIndex = 7
optOperation(5).TabIndex = 8
End Sub
Private Sub cmdCancel_Click()
' When the user clicks on the Cancel button, unload the form.
Unload Me
End Sub
Private Sub cmdEval_Click()
' Declare the variables to be used in the code
Dim data1 As Range
' This is the temporary variable that holds the value entered in
' the spreadsheet.
'Dim finalRows As Double ' The number of
'Dim finalCols As Double
' Dim tempVal As Double
Dim matArray1 As Variant ' Variable to hold the value of input Matrix 1,
' passed to the COM object directly.
Dim matArray2 As Variant ' Variable to hold the value of input Matrix 1,
' passed via varArg variable.
Dim matArray3 As Variant ' Variable to hold the value of input Matrix 1,
' passed via varArg variable.
Dim varArg(2) As Variant ' Variable to hold the value of input Matrix 1,,
' contains the two optional matrices and is passed to the COM object.
'Dim mat1() As Double
'Dim mat1Dimension2() As Variant
Dim tempRange As Range ' Take the range value as obtained from the
' user input into a temporary range.
Dim resultMat As Variant ' Variable to take the result matrix in
Dim msg As String ' The message thrown by the COM object is taken
' in this variable.
Call sheetResultMat.ActiveSheet.UsedRange.Clear
' Check if the COM object was created properly.
' If not exit
If theMatCal Is Nothing Then GoTo exit_form
' Get the used range of data from the sheetMat1, which will then be
' converted into matArray1.
Set data1 = sheetMat1.ActiveSheet.UsedRange
'finalRows = data1.Rows.Count
'finalCols = data1.Columns.Count
'ReDim mat1(1 To data1.Rows.Count)
'ReDim mat1Dimension2(1 To data1.Columns.Count)
ReDim matArray1(1 To data1.Rows.Count, 1 To data1.Columns.Count) As_
Double
For RowCount = 1 To data1.Rows.Count
For ColCount = 1 To data1.Columns.Count
' Extract the values and populate input matrix 1.
Set tempRange = data1.Cells(RowCount, ColCount)
'tempVal = tempRange.Value
'matArray1(RowCount, ColCount) = tempVal
matArray1(RowCount, ColCount) = tempRange.Value
'Set mat1(ColCount) = tempRange.Value
Next ColCount
' mat1Dimension2(RowCount) = mat1()
Next RowCount
Set data1 = sheetMat2.ActiveSheet.UsedRange
If (Not (data1.Value = "")) Then
ReDim matArray2(1 To data1.Rows.Count, 1 To data1.Columns.Count) As_
Double
For RowCount = 1 To data1.Rows.Count
For ColCount = 1 To data1.Columns.Count
Set tempRange = data1.Cells(RowCount, ColCount)
tempVal = tempRange.Value
matArray2(RowCount, ColCount) = tempVal
Next ColCount
Next RowCount
finalCols = data1.Columns.Count
varArg(0) = matArray2
End If
Set data1 = sheetMat3.ActiveSheet.UsedRange
If (Not (data1.Value = "")) Then
ReDim matArray3(1 To data1.Rows.Count, 1 To data1.Columns.Count) As_
Double
For RowCount = 1 To data1.Rows.Count
For ColCount = 1 To data1.Columns.Count
Set tempRange = data1.Cells(RowCount, ColCount)
tempVal = tempRange.Value
matArray3(RowCount, ColCount) = tempVal
Next ColCount
Next RowCount
finalCols = data1.Columns.Count
varArg(1) = matArray3
End If
' Based on the operation selected by the user, call the appropriate method
' from the COM object.
If optOperation.Item(0).Value = True Then ' Add
Call theMatCal.addMatrices(2, resultMat, msg, matArray1, varArg)
ElseIf optOperation.Item(1).Value = True Then ' Subtract
Call theMatCal.subtractMatrices(2, resultMat, msg, matArray1, varArg)
ElseIf optOperation.Item(2).Value = True Then ' Multiply
Call theMatCal.multiplyMatrices(2, resultMat, msg, matArray1, varArg)
ElseIf optOperation.Item(3).Value = True Then ' Divide
Call theMatCal.divideMatrices(2, resultMat, msg, matArray1, varArg)
ElseIf optOperation.Item(4).Value = True Then ' Left Divide
Call theMatCal.leftDivideMatrices(2, resultMat, msg, matArray1,_
varArg)
ElseIf optOperation.Item(5).Value = True Then ' Eigen Value
Call theMatCal.eigenValue(2, resultMat, msg, matArray1)
End If
' If the result matrix is a scalar double, display it in the first cell.
If (VarType(resultMat) = vbDouble) Then
Set tempRange = sheetResultMat.Cells(1, 1)
tempRange.Value = resultMat
' If the result matrix is not a scalar double, loop through it to display
' all the elements.
Else
For RowCount = 1 To UBound(resultMat, 1)
For ColCount = 1 To UBound(resultMat, 2)
Set tempRange = sheetResultMat.Cells(RowCount, ColCount)
tempRange.Value = resultMat(RowCount, ColCount)
Next ColCount
Next RowCount
End If
Exit Sub
exit_form:
MsgBox ("Error: " & Err.Description)
Unload Me
End Sub
' If the user changes the operation, clear the result matrix.
Private Sub optOperation_Click(Index As Integer)
Call sheetResultMat.ActiveSheet.Cells.Clear
End Sub
![]() | Univariate Interpolation Example | Curve Fitting Example | ![]() |

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 |