Problem to get m-code work with user-defined functions (e.g. persisent)
1 view (last 30 days)
Show older comments
Hello,
i'm really new to matlab and wrote some m script code and now i want to use this code in a model that i created with simulink - simscape. I found out thats possible to use the user-defined functions to solve that problem. I'm using the MATLAB Function Block to execute my code but i'm struggeling in initalizing a persistent variable. Here is a snipped out of my code:
function [O_y_m, O_Net_Weights, O_Stepsize_Weights] = rbf_net(input_flag,u_old,y,y_old)
%#codegen
persistent NET_CENTERS;
NET_INPUT = 3;
NET_HIDDEN = 6;
if(input_flag == 0) %also tried if(isempty(NET_CENTERS))
NET_CENTERS = randn(NET_HIDDEN,NET_INPUT);
end
X = [u_old, y, y_old];
H = zeros(NET_HIDDEN,1);
for j = 1:NET_HIDDEN
ekl_dist = norm (X-NET_CENTERS(j));
H(j) = exp(-(ekl_dist)/(2 * B(j)^2));
end
I get the following error:
Persistent variable 'NET_CENTERS' is undefined on some execution paths.
Matlab provides this to initalize a persistent variable
function findProduct(inputvalue) %#codegen
persistent PROD_X
if isempty(PROD_X)
PROD_X = 1;
end
PROD_X = PROD_X * inputvalue;
end
Already tried this before. It only works in the m-code.
Maybe this is the wrong way of using it but i try to explain what i want to do: I need something like a global variable for my function that must be a matrix and should only initialized at sample time 0. The Dimension will be determined by two constants that i will change from time to time (not in the code, only a manual way after i evaluated the results of my model). This matrix must be updated in the function and it values must be also there, when the function will be executed at the next sample time.
Thanks for your further help!
with kind regards
2 Comments
Answers (2)
Image Analyst
on 13 May 2015
I don't know Simscape but it thinks that this line
if(input_flag == 0)
NET_CENTERS = randn(NET_HIDDEN,NET_INPUT);
end
may not get executed if you never pass in a flag of 0. And later on you go on to use NET_CENTERS in a for loop which definitely will get executed. Well, if NET_CENTERS never got assigned, then the line in the for loop will bomb. That's what it's warning you about. And I think it's probably a warning rather than an error. You can either ignore it, or (better and more robust) initialize it after checking if it's empty by using isempty(), like your MATLAB example function did.
% Add this if block to initialize in case NET_CENTERS has not been assigned yet.
if isempty(NET_CENTERS)
NET_CENTERS = randn(NET_HIDDEN,NET_INPUT);
end
See Also
Categories
Find more on Foundation and Custom Domains in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!