11.7: Using MATLAB Variables in Simulink

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    11.7: Using MATLAB Variables in Simulink

    One of the useful features of Simulink is that it is connected to MATLAB. This means you can define variables in MATLAB and then use those variable names inside Simulink blocks.

    For example, in MATLAB, define two variables:

    C1 = 3;
    C2 = 5;
    
    

    clipboard_ec10f0c2ed21a9c6fc6062148d19ed7e8.png

    Then, in Simulink, double-click the Constant blocks and set the Constant values to C1 and C2 instead of typing numbers directly. When the model runs, Simulink looks in the MATLAB workspace, finds the values of C1 and C2, and uses those values in the model.

    clipboard_e7176d019f23ab02ce0c43f2fc7ec9f52.png

    This approach is helpful because you can change the values in MATLAB without editing the Simulink blocks. For example, you could run the same model several times with different input values.

    You can also use arrays as Simulink inputs. In MATLAB, type:

    C1 = [1 3 5 7];
    C2 = [2 4 6 8];
    


    clipboard_ea0c696a4d60a1be1abef24f0f9686bdc.png

    If the Constant blocks use C1 and C2, and they are connected to a Sum block, Simulink will add the arrays element-by-element. The result will be:

    [3 7 11 15]
    
    

    clipboard_edc6756631bf3ce6f54377a42f7bbf5a2.png

    Caution

    Important warning
    If a Simulink block uses a MATLAB variable and that variable is not defined in the MATLAB workspace, the model will not run. This often happens if you clear the workspace and forget to redefine the variables.

    Initializing Variables Inside the Simulink Model

    A good habit is to initialize important variables inside the Simulink model itself. This makes the model more reliable because it can still run even if the MATLAB workspace has been cleared.

    1. Go to Modeling Tab.

    2. Open Model Settings, Model Properties.

    3. Open the Callbacks tab.

    4. Choose InitFcn, which stands for initialization function.

    5. Type the variable definitions, such as C1 = 5; and C2 = 3;.

    6. Apply and run the model.

    clipboard_e8744c15c111cdda7e1510564a4b3d512.png

    clipboard_e63d6827e4e9cc7e7ca85d61639bd1b71.png

    Now the model defines the variables before the simulation begins. This is especially useful when you share your model with someone else.


    This page titled 11.7: Using MATLAB Variables in Simulink was last modified on Tue, 30 Jun 2026 02:11:50 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.