Initialising variables in an embedded function

5 views (last 30 days)
Hello everyone,
I'm trying to get an embedded function within Matlab Simulink to perform a finite difference calculation for me.
The idea is that the output argument will be fed back into itself after a unit delay in order for the next set of values to be computed by the function.
The problem is that I can't seem to initialise output variables.
I'm unable to declare the output variable as persistent as Matlab won't allow it... Here is my code:
function Temps = fcn(Ti,aw,aa,L,Tstep,Tamb,Tcline,Tprev)
%#eml
Nodes = 100;
persistent Temps;
if isempty ( Temps );
Temps = [1:1:Nodes]./[1:1:Nodes];
end
for k = 1:Nodes;
if k>2;
Tnew(k) = aw.*Temps(k-1)+0.2*k;
else
Tnew(k) = 1;
end
end
Temps = Temps.*Tnew
end
And here is the error:
The PERSISTENT declaration cannot be used on function outputs.
Function 'Finite Difference Conduction Calculator' (#31.76.86), line 4, column 1:
"persistent"
Thanks in advance
Pete

Accepted Answer

Kaustubha Govind
Kaustubha Govind on 1 Aug 2012
Why not use a local variable as the persistent variable instead?
function output = fcn(Ti,aw,aa,L,Tstep,Tamb,Tcline,Tprev)
%#eml
Nodes = 100;
persistent Temps;
if isempty ( Temps );
Temps = [1:1:Nodes]./[1:1:Nodes];
end
for k = 1:Nodes;
if k>2;
Tnew(k) = aw.*Temps(k-1)+0.2*k;
else
Tnew(k) = 1;
end
end
Temps = Temps.*Tnew;
output = Temps;
end

More Answers (2)

Mike Hosea
Mike Hosea on 1 Aug 2012
Right. The output variable cannot be a persistent variable. There's more than one way to go about this, but all involve using two variables where now you're trying to use one. Perhaps the simplest solution is to rename your output variable and make the last line of your code a copy from the persistent variable to the output variable. Something like
function yout = foo(x)
persistent yp
if isempty(yp)
yp = x;
end
<Some calculations involving only x and yp go here.>
yout = p;

Peter
Peter on 2 Aug 2012
Dear All,
Thanks very much for the rapid response, it turns out that simply renaming the variable works perfectly.
Azzi, I like your suggestion of initialising the unit delay I hadn't thought of it and I guess that would have worked too.
Best Regards
Pete Armstrong

Categories

Find more on Simulink Environment Customization in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!