0
votes

I need to use a Matlab function inside of a Simulink model. I know how to use a Matlab function to do simple stuff. But what I need now is a little bit more complicated. Let me give you a basic example.

Assume that I need to have a block to generate a sine wave to be viewed directly on the scope (I know that there is already a sine-wave block, I'm just taking that as an example). If I'm writing in Matlab NOT in Simulink, I would do something like:

 t = [0:1/30000:0.2];
 A = 1;
 f =10000;
 y = A*sin(2*pi*f*t);
 plot(t(1:100),y(1:100))

How can I build the same function inside a Simulink matlab-function block and see the results directly on the Scope?

Remember: The Matlab Function Block has two ports, u and y. Which represents input and output respectively. In the above-given example, a sine-wave generator doesn't need an input.

1
You can configure the number of ports of a matlab function block.Daniel

1 Answers

2
votes

Perhaps it's just that you haven't chosen a very good example, but there are several things to be aware of when translating the code you've given into Simulink.

  1. The easiest way to get the simulation time into a MATLAB Function block is by feeding a Clock block into an input port (which as @Daniel indicates, are optional, but in this case I suggest would be used for t). So I think you do want an inport in this example.

  2. Your use of plot in your example only plots the first 100 points, where as a Simulink Scope rolls through the data being displayed. There's no concept of only displaying the first X points in a Scope when the simulation runs for longer than that.

  3. You need to remember that Simulink generates data one simulation time step at a time, so you can't generate them all (as per your MATLAB code) and then plot them all. (Well... you can if you want to use frame based signals, but I assume that's not what you're asking here.)

So, to implement the equivalent of what you have would involve doing the following.

  • write a MATLAB Function block containing the following code (although you might want to make A and f input parameters rather than hard coding them)

    function y = myCustomSineWave(t) A = 1; f =10000; y = A*sin(2*pi*f*t);

  • Feed a Clock block into the above block, and have a Scope block on its output