Masoom Kumar
Masoom Kumar

Reputation: 149

Assign vectors from MATLAB workspace (struct) to Simulink Model

I need help with running a Simulink model with the data from MATLAB workspace contained in structures. Below is a very simplified use-case of what I would like to do

Use Case :

I have a structure in MATLAB workspace called "data_in", and it has two fields x, and y which are vectors. I have a simulink model with two Inports named x and y.

This is what I would like to to :

a. Read the name of the Inports from the Simlunk Model. In this case it would be x and y

b. Programmatically assign the data from the structure - "data_in" to the ports "x" and "y" in the Simulink model. The structure "data_in" contains two vectors "x" and "y" to be mapped to Simulink Inports

The above use case is a very simplified scenario. The model that I intend to use can have 100 inports, and thus I do not want to use "From Workspace" block, as it would be impractical for me to add 100s of them

How can I handle such a situation in Simulink. I am a little more than a beginner in MATLAB and Simulink. So, a detailed answer would help me a lot

Upvotes: 1

Views: 877

Answers (1)

Shivid
Shivid

Reputation: 1343

If I get correctly your question, and the inputs are time-variables, you may use From Workspace and call your initialization script by InitFcn in Callbacks.

assuming you have an initialization script named init_script:

put in InitFcn this: init_script; so as you run Simulink that script is run first.

assume this is your timeseries in init_script:

ts = timeseries(randn(10,2),'Name','TS');

put ts in the From Workspace: enter image description here

But if these are not time variant vectors do the same and use constant block instead, inside its value field put the vectors' name and again put the script that contains these vectors in InitFcn in Callbacks:

X = randi(10,6,1); 
Y = randi(10,6,1);

then do the operations you need: enter image description here

so the To Workspace block named as simout will give you:

simout.Data(:,:,1)
ans =

14
 9
16
16
10
 3

and finally, if you have lots of those vectors and components, you can create them easily from Matlab Workspace:

my_struct.x = randn(6,1);my_struct.y = randn(6,1);
new_system('myModel')
open_system('myModel')
pos = [10   10   20   30]
for i =1:10
    add_block('built-in/Inport',['myModel' '/In1'],'Position',pos);
    add_block('built-in/Constant',['myModel' strcat('/Cx', num2str(i))],'Position',pos+2);
    add_block('built-in/Constant',['myModel' strcat('/Cy', num2str(i))],'Position',pos+i);
    pos = pos + 1;
    X_vector = my_st.x
    set_param(strcat('myModel/Cx', num2str(i)),'Value', X_vector)
    Y_vector = my_st.x
    set_param(strcat('myModel/Cy', num2str(i)),'Value', Y_vector)
....

of course this for loop code is here to give you the idea, and in reality will be more complex and you will know how to handle it the best.

Upvotes: 1

Related Questions