How to use inside a Simulink file a user-defined class previously written in matlab?

Dear reader,
I have created a simple class given below:
classdef dummy3
properties
a = 0;
b;
end
methods
%constructor
function obj = dummy3(a,b)
% class constructor
if(nargin > 0)
obj.a = a;
obj.b = b;
end
end
end
methods(Static = true)
function value = roll(numdays)
value = numdays;
end
end
end
and let the object P be defined as:
P = dummy3(1,2)
The question is how can I use the variable P.a and how can I call the method P.roll(rand(1)) inside a Simulink file? For convenience, I'd prefer to use them inside a Matlab function, like this scheme:
where I've tried to place inside the code
y = P.a
which resulted in error "Undefined function or variable 'P'." Furthermore, replacing this line by
y = P.roll(rand(1))
yields the same error. I cannot understand why since I did add into File -> Model Properties -> Callbacks -> InitFcn the line of code
P=dummy3(1,2)
Thank you for your help.

 Accepted Answer

I found 2 main issues here:
First, methods of a class must have the object itself as the first argument. So, to correctly use the roll method, you may want to redefine it as:
function value = roll(obj,numdays)
Secondly, you need to create the object P in your MATLAB Function block. In other words, prior to calling P.roll(4), you should say:
P = dummy3(a,b);
val = P.roll(4);
- Sebastian

3 Comments

Hi Sebastian,
Thanks for your post. Your solution regarding the second issue seems to work in Simulink. However this implementation has one big drawback: at each sampling time the object P needs to be created over and over, whereas it does not change at all from one sample time to another. I have the feeling this will slow down simulations execution time.
Instead, I would have preferred P to be created just once at the beginning of simulations (since object P does not modify at all throughout simulations) and only use its propery P.a and call the method P.roll(rand(1)) inside a Matlab function. By doing so, I am hoping to achieve faster simulations. Any idea how to achieve this?
Thank you.
Yes -- sorry, I should have mentioned that. You can make P a persistent variable so it is created only on the first execution of the model.
persistent P;
if isempty(P)
P = dummy3(a,b);
end
- Sebastian
Thank you very much for your time. I confirm this is indeed the functionality that I have been looking for. Additionally I have checked that it can be used for code generation purpose.

Sign in to comment.

More Answers (0)

Categories

Products

Asked:

on 16 Jun 2015

Commented:

on 17 Jun 2015

Community Treasure Hunt

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

Start Hunting!