4

I would like to have some file, myfunc.m, in my MATLAB path and somehow load its contents into a MATLAB function block automatically just before the simulation starts. This way, I can use an external editor to write these embedded function, version control them separately as independent files, etc.

Is there a way to achieve this programmatically?

My initial attempt was to try and access the contents of the function block using something like get_param, but I can't seem to gain read/write access to the code itself.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
safwanc
  • 3,351
  • 2
  • 15
  • 20
  • Do you really need to modify the function block or is it acceptable to use a function block that does nothing else but call `myfunc`? – mars Apr 26 '12 at 14:46
  • How is calling it right before the simulation start and at the start of the simulation any different? – Rasman Apr 26 '12 at 14:55
  • @mars: I would prefer to modify it directly because I _think_ calling `myfunc` with something like `eml.extrinsic` or just using a block that calls a function in the MATLAB workspace slows down the overall performance. – safwanc Apr 26 '12 at 16:38

3 Answers3

2

If the target MATLAB Function block doesn't already exist then you can add it as follows (see this SO post):

load_system('eml_lib');
libname = sprintf('eml_lib/MATLAB Function');
add_block(libname,'myModel/myBlockName');

You can then modify the block's code using the Stateflow API:

sf = sfroot();
block = sf.find('Path','myModel/myBlockName','-isa','Stateflow.EMChart');
block.Script = 'Your code goes here';

See also this post on MATLAB Answers.

Community
  • 1
  • 1
Florian Brucker
  • 9,621
  • 3
  • 48
  • 81
1

First, you will need to add the folder containing the m-file to the default path. To do this:

(In the Command window) Go to File -> Set Path -> Add Folder (choose the folder containing the m-file)

Now, you should use the InitFcn callback in the model properties to call your function. To do this, open the model:

(In the Model window) Go to File -> Model Properties -> Callbacks -> InitFcn In the edit box provided for the InitFcn, write the command to call your function i.e. myfunc(); You will have to modify this command as per your function and requirements.

Once done, apply the changes to the Model Properties window and simulate the model.

Akanksha
  • 96
  • 8
0

I am thinking that model callbacks may be a way to do what you want, though I have not used this technique myself.

KAE
  • 815
  • 1
  • 13
  • 32