getting data from mfile to simulink

I have a set of code which is working fine when i run it individually as matlab script. Now, I have made a model in simulink and i want my model to get the values from that matlab script. For ex- instead of specifying the value of 'A' in simulink model, i want the value of A to be imported from my mfile whenever i run my simulink model. Please help

 Accepted Answer

For this kind of situation, the best thing to do is to use From Workspace block. But its usage is a little different, so let me try to explain with a small example. All you need to do is to define A in workspace(this is compulsory, or you can define the necessary values in File->Model Properties->Callbacks->PreLoadFcn) and do the following:
Imagine that your A value, either a scalar or a vector, has to be supplied to your Simulink model with a proper time vector which will imitate Simulink's simulation time. For instance, a numeric approach:
A=randi([1 10],1001,1);
A is a column vector with length of 1001. Then, your time vector also has to be length of 1001. Then, you need to form 1001x2 multidimensional array as
time=0:0.001:10;
%column vector
time=time(:);
data=[time A];
When you write the variable data into the From Workspace block, Simulink will automatically know that the first column is the time vector, starting from the second column(could have been more A vector), datas will be coming. This approach is the best and simplest for supplying data from workspace to Simulink model.

3 Comments

Thankyou so much for the help
If i can ask one more question that..
if you look at various examples of matlab, they make the model in simulink but for the naming of constants and various other parameters like Fnom, Tnom, Ts_power, Ts_freq or any other constant..they directly write Fnom and specify all these values in a separate mfile or script. Then how do they connect that script file with their simulink model. And when everytime you run the simulation those values are already initialized by that file? Please suggest..
Actually, for the situation you mentioned, if you want to preinitialize the variables when the model is opened, you should use File->Model Properties->Model Properties->Callbacks. In this section, there are several function types, for preinitializing, you need to write your script to PreLoadFcn and you should be fine.
Works well. Thankyou

Sign in to comment.

More Answers (1)

Use a From Workspace block in the model. At the matlab level, initialize the variable, and then start the model executing by using the sim() call.

Categories

Find more on Simulink in Help Center and File Exchange

Asked:

on 21 Dec 2017

Commented:

on 22 Dec 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!