Simulink: MATLAB Function Doesn't Recognise Variables

32 Ansichten (letzte 30 Tage)
MATLAB_Soldier
MATLAB_Soldier am 15 Nov. 2022
Beantwortet: cr am 15 Nov. 2022
Hi All,
I have created this a MATLAB Function in simulink which I would like to run. This function uses certain variables which I have loaded in through the PreLoadFcn as follow:
This is the code inside my function:
function G = fcn(v,vp,gp)
if v <= Up2 & vp < Up2 | v <= Dn1 & vp > Dn1;
G=1;
elseif Up2 < v & v <= Up3 & vp < Up3 | Dn1 < vp & vp < Dn2;
G=2;
elseif Up3 < v & v <= Up4 & vp < Up4 | Dn2 < vp & vp < Dn3;
G=3;
elseif Up4 < v & v <= Up5 & vp < Up5 | Dn3 < vp & vp < Dn4;
G=4;
elseif Up5 < v & v <= Up6 & vp < Up6 | Dn4 < vp & vp < Dn5;
G=5;
elseif Up6 < v & Up6 < vp | Dn5 < v & Gp==6
G=6,
else
disp("LOGIC ERROR")
end
I saved the simulation and reopened it. Then, I get these error messages after I click on the run button:
Why does the function not able access the variables above?

Akzeptierte Antwort

cr
cr am 15 Nov. 2022
Of course it doesn't. That is intended behaviour. Functions have their own workspace which is distinct from base workspace (or model workspace). If you need the function to use the variables/parameters declared in preloadfcn, you must pass in these variables separately. You may use a from workspace block and input it to additional input port(s) on the fcn block. Your fcn definition may become something like
function G = fcn(v,vp,gp,Up1,Up2,Up3,Up4,Up5,Dn1,Dn2,Dn3,Dn4,Dn5)
or better, mux all ups and dns into two signals, say ups and dns and use
fcn(v,vp,gp,ups,dns)
Regards

Weitere Antworten (0)

Kategorien

Mehr zu Simulink Functions finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by