0
votes

I want to use a persistent variable inside a matlab function block but I can't initialize it. I want to either initialize it from an m.file or do it inside the function.

If I use isempty then the variable is given a size of 1x1 and I don't want that. Basically I don't know how to handle the persistent value as it is taken as 1x1 or as not defined. How can I use isempty but do not give it a 1x1 size? Or how can I initialize it from an m.file?

function y1 = fcn(u)

persistent y;

if isempty(y)
y=0;
end

for i=1:1:length(u)
    if u(1,i) >=10
       y(1,i) = 1;
    elseif u(1,i) <= 5
       y(1,i) = 0;
    else 
        ;
    end
end

y1=y;

end
1
@Jigg,My persistent variable is fixed in size, let's say a vector 1x10. It changes with time since the system is dynamic. I just want it to be set to zeros only once and not every time the function is called. With isempty in the function I get 1x1 and I can't do it through workspace/m.file. - Engineer
@Jigg, Of course, since the variable is empty in the beginning it is a way to initialize it. It's also stated in matlab help for that reason. I will update the post with the code. - Engineer
As I told you it is a dynamic system, so the initialization is not important. It will run after some time properly whatever these initial conditions are. - Engineer

1 Answers

1
votes

You are initializing y to a scalar. If you want to initialize it to an empty vector of zeros, use y=zeros(1,n) where n is the number of elements you want it to have.