matlabscriptingsimulink

Expression to Simulink Model Conversion


The input will be a string (eg.'X+Y+Z') and the output must be a Simulink Model(slx file). This should be done using m-script. The Simulink Model should be dynamic(the model must be according to the input expression provided - if input expression changes, the model generated must be corresponding to the input expression. The X,Y,Z are the constant blocks with values X,Y,Z respectively.

Assumptions - ->The variables are X, Y and Z only. The operators can be any of the following(+,-,*,/). ->Implement the Multiplication operator using Product Block. ->No coefficients are present for the X,Y,Z variables.

My Approach - I used RegExp to extract the terms and operators. All the terms(X,Y,Z) are present in 'terms' cell array and operators are obtained in the 'operators' cell array.

Next, I thought of using the 'Stack' concept to solve this problem. I first stored the terms(X,Y,Z) in the stack in reverse order of their occurence in the expression. Then, I used the top 2 terms in the stack to create their respective Add Blocks. For this I have used the 'add_block' function. But I m unable to give the unique names to these blocks, as the block names must be unique.

And, I am unable to connect these constant blocks to the Add Block.

I am stuck at this position. Please provide me the best and optimized approach to solve this problem.


Solution

  • To make a name unique while programmatically adding blocks to to a simulink model there is a name-value field in the add_block. Please refer to add_block documentation:

    h = add_block(source,dest,'MakeNameUnique','on') ensures that the destination block name is unique in the model. This syntax adds a number to the destination block name if a block with that name exists, incrementing to ensure a unique name.

    so:

    add_block('Simulink/Math Operations/Sum','<yourprojectname>/<nonuniquename>','MakeNameUnique','on')
    

    Otherwise, since you are not blindly generating but the structure and number of blocks is known you could set the name of the block upon creation with the add_block dest field iself:

    add_block('Simulink/Math Operations/Sum','<yourprojectname>/<uniquename>');
    

    so for example:

    add_block('Simulink/Math Operations/Sum','<yourprojectname>/XYaddition');
    add_block('Simulink/Math Operations/Sum','<yourprojectname>/XYaddition');