Skip to Main Content Skip to Search
Product Documentation

Curve Fitting Example

Example Overview

This example demonstrates the optimal fitting of a nonlinear function to a set of data, using the curve-fitting demo fitfun provided with the MATLAB product. It uses fminsearch, an implementation of the Nelder-Mead simplex (direct search) algorithm, to minimize a nonlinear function of several variables.

This example shows you how to create the COM component using the MATLAB Builder NE product and how to use this COM component in a Microsoft Visual Basic application independent of MATLAB.

Building the Component

  1. At the MATLAB command prompt, change folders to matlabroot.

  2. Enter the deploytool command to open the Deployment Tool window.

  3. Create a project with the following settings:

    Project nameCurveFit
    Class nameCurveFitclass

Building the Project

  1. In the Deployment Tool window, add fitfun.m and fitdemo.m from the folder matlabroot/CurveFitDemo.

  2. Click the button in the toolbar.

    The component is created and placed in the distrib folder within the Classfolder.

Using the Component in Microsoft Visual Basic

You can call the component from any application that supports COM.

Open CurveFitComp.vcproj or create a Microsoft Visual Basic project and add references to the necessary libraries:

  1. Start Visual Basic.

  2. Create a new Standard EXE project.

  3. Select Project > References.

  4. Ensure that the following libraries are included in the project:

    CurveFit 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.

Creating the Microsoft Visual Basic Form

The next step is to create a front end or a Microsoft Visual Basic form for the application. End users enter data on the form.

To create a new user form and populate it with the necessary controls:

  1. Select Projects > Component. Alternatively, press Ctrl+T.

  2. Make sure that Microsoft Windows Common Controls 6.0 is selected. You will use the ListView control from this component library.

  3. Add a series of controls to the blank form to create an interface.

    The following table shows the components and properties that are required.

    Control TypeControl NamePropertiesPurpose

    Form

    frmCurveFit

    Caption = Curve Fitting

    Container for all components.

    Frame

    frmInput

    Name = frmInput*

    Caption = Input Data Points

    Groups all input controls.

    Frame

    frmOutput

    Name = frmOutput*

    Caption = Output Coefficients

    Groups all output controls.

    Label

    lblNumDataPoints

    Caption = Number of Data Points

    Labels the text box that takes the number of data points the user wants to enter.

    TextBox

    txtNumOfDatPoints

    Text =

    Holds number of data points the user wants to enter. Sets size of list box added later.

    ListView

    lstXData

    Name = lstXData

    GridLines = TrueLabel

    Edit = lvwAutomatic

    View = lvwReport

    X-data values. Set the view type to lvwReport to enable user to add data to the list view.

    ListView

    lxtYData

    Name = lstYData

    GridLines = TrueLabel

    Edit = lvwAutomatic

    View = lvwReport

    Y-data values.

    Label

    lblCoeff1*

    Caption = Co-efficient 1

    Labels text box for coefficient 1.

    Label

    lblCoeff2

    Caption = Co-efficient 2

    Labels text box for coefficient 2.

    TextBox

    txtCoeff1

    Text =

    Displays value of coefficient 1 as calculated by the COM module.

    TextBox

    txtCoeff2

    Text =

    Displays value of coefficient 2 as calculated by the COM module.

    Label

    lblLambda1*

    Caption = Lambda 1

    Labels text box for lambda 1.

    Label

    lblLambda2

    Caption = Lambda 2

    Labels text box for lambda 2.

    TextBox

    txtLambda1

    Text =

    Displays value of lambda 1 as calculated by the COM module.

    TextBox

    txtLambda2

    Text =

    Displays value of lambda 2 as calculated by the COM module.

    CommandButton

    cmdEvaluate

    Caption = Evaluate

    Default = True

    Executes function.

    CommandButton

    cmdCancel

    Caption = Cancel

    Cancel = True

    Closes dialog box without executing the function.

  4. When the design is complete, save the project by selecting File > Save.

  5. When prompted for the project name, type CurveFitExample.vbp, and for the form, type frmCurveFit.frm.

  6. In the Project window, right-click frmCurveFit 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 theFit As CurveFit.CurveFit ' Variable to hold the COM Object
    
    ' This routine is exectued when the form is initialized.
    Private Sub Form_Initialize()
    ' If the initialize routine fails, handle it accordingly.
    On Error GoTo Exit_Form
        ' Create the COM object
        Set theFit = New CurveFit.CurveFit
        ' Set the flags such that the output is transposed.
        theFit.MWFlags.ArrayFormatFlags.TransposeOutput = True
        Exit Sub
    Exit_Form:
        ' Display the error message and Unload the form if object 
    creation failed
        MsgBox ("Error: " & Err.Description)
        MsgBox ("Error: Could not create the COM object")
        Unload Me
    End Sub
    
    Private Sub Form_Load()
    On Error GoTo Exit_Form
        ' Set the run-time properties of the components
        
        ' Set the headers of the column
        Call lstXData.ColumnHeaders.Add(, , "X Data")
        Call lstYData.ColumnHeaders.Add(, , "Y Data")
        
        ' Make labeledit property automatic so that you edit the label.
        lstXData.LabelEdit = lvwAutomatic
        lstYData.LabelEdit = lvwAutomatic
        
        ' Make the grid lines for the listbox visible.
        lstXData.GridLines = True
        lstYData.GridLines = True
        Exit Sub
    Exit_Form:
        ' Error handling routine. Since cannot load the form, 
        ' display the error message and unload the program.
        MsgBox ("Error: Could not load the form")
        MsgBox ("Error: " & Err.Description)
        Unload Me
    End Sub
    
    Private Sub cmdCancel_Click()
        ' If the user hits the cancel button, unload the form.
        Unload Me
    End Sub
    
    Private Sub txtNumOfDataPoints_Change()
        ' If user changes number of data points, clear XData and YData 
        ' listboxes. Provide enough spaces for given number of points.
        Dim loopCount As Integer
        Call lstXData.ListItems.Clear
        Call lstYData.ListItems.Clear
        If (txtNumOfDataPoints.Text = "") Then
            Exit Sub
        End If
        For loopCount = 1 To CInt(txtNumOfDataPoints.Text)
            lstXData.ListItems.Add (loopCount)
            lstYData.ListItems.Add (loopCount)
        Next loopCount
    End Sub
    
    Private Sub cmdEvaluate_Click()
        Dim loopCount As Integer ' loop counter
        Dim numOfData As Integer ' variable to hold the number of data 
                                 ' points the user has entered
        Dim XData() As Double ' Column Vector for XData, will be passed 
                              ' as input to the COM method.
        Dim YData() As Double ' Column Vector for YData, will be passed 
                              ' as input to the COM method.
        Dim Coeff As Variant ' Coefficient values will be returned by 
                             ' the COM method in this variable.
        Dim Lambda As Variant ' Lambda values will be returned by the 
                              ' COM method in this variable.
        
        ' If there is an error, handle it accordingly.
    On Error GoTo Handle_Error
        If txtNumOfDataPoints.Text = "" Then
            Exit Sub
        End If
        ' Get the number of data points.
        numOfData = CInt(txtNumOfDataPoints.Text)
        ReDim XData(1 To numOfData) As Double
        ReDim YData(1 To numOfData) As Double
        ' Read the input data into respective double arrays.
        For loopCount = 1 To numOfData
            XData(loopCount) = lstXData.ListItems.Item(loopCount)
            YData(loopCount) = lstYData.ListItems.Item(loopCount)
        Next loopCount
        
        ' Call the COM method
        Call theFit.fitdemo(2, Coeff, Lambda, XData, YData)
        
        ' Display values of coefficients returned by the COM method.
        txtCoeff1.Text = CStr(Format(Coeff(1, 1), "##.####"))
        txtCoeff2.Text = CStr(Format(Coeff(1, 2), "##.####"))
        txtLambda1.Text = CStr(Format(Lambda(1, 1), "##.####"))
        txtLambda2.Text = CStr(Format(Lambda(1, 2), "##.####"))
        Exit Sub
    Handle_Error:
        ' Error handling routine
        MsgBox ("Error: " & Err.Description)
    End Sub
    

  


Recommended Products

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