Max
Max

Reputation: 1481

Saving a specific simulation time

I have a two-track model implemented in simulink. To control the velocity I use a PID-controller, so that the the output of the velocity looks like this:

simulink

now I want to implement a MATLAB function or simulink block that tracks the time when the velocity reaches a steady-state-behaviour and puts it into some kind of storage. I tried to implement something like this via the following MATLAB function with MATLAB-function-block:

function y = fcn(t,v,dv,tv)
  %#codegen
  if (v==tv+0.01) & (dv<0)
  y=t
end

t is the clock-signal, v the velocity, dv the first derivation of the velocity and tv is the targetvelocity. The problem about this function is that there "y is not defined on some execution paths". do you have any ideas how to make this work?

Upvotes: 1

Views: 817

Answers (3)

Adriaan
Adriaan

Reputation: 18177

function y = fcn(t,v,dv,tv)
  %#codegen
y = zeros(length(t),1); % Initialise the array
for ii = 1:length(t)
  if (v==tv+0.01) & (dv<0)
  y(ii)=t;
  else
  y(ii)=0;
  end
end
y(y==0)=[];
end

Two changes: added a semicolon after y=t to force it to not print it every time it is set. Second, your question, else y=[];, which means that y will be an empty matrix if you do not adhere to your if statement.

It now stores a 0 each time you do not adhere to the if statement. The line y(y==0)=[]; deletes all zeros, comment this line if you want your y to be the same length as the input variables.

function y = fcn(t,v,dv,tv)
  %#codegen
y = zeros(length(t),1); % Initialise the array
ii=1;
while exist(t)
  if (v==tv+0.01) & (dv<0)
  y(ii)=t;
  else
  y(ii)=0;
  end
ii = ii+1;
end
y(y==0)=[];
end

Upvotes: 3

Matt
Matt

Reputation: 2802

In SimuLink add a second output and a fifth input to your function. Then use that new output as a feedback to the function.

function [y, output] = fcn(t,v,dv,tv,input)
y = 0;
output = input;
if (v == tv + 0.01) && (dv < 0)
    y = t;
    if (input == -1)
        output = t;
    end
end

Attach the output to an IC block where you set the input initial value to -1 or whatever value you want to use. Then attach the IC block to the input of the function. output will be feedback constantly through the function. Once it's set it will reatin it's value forever.

Upvotes: 3

Max
Max

Reputation: 1481

simulink

I solved the problem without a MATLAB function using the simulink blocks data store memory and its read & write blocks. The signal that is coming in from bottom right side is the momentary velocity. The if statement is

(u1 >= 22.2) & (u1<=22.3) & (u2<0)

Since simulink is using time steps and the momentary velocity will never be exactly 22.2, you can not use u1==22.2

Upvotes: 4

Related Questions