Simulink: MATLAB Function Doesn't Recognise Variables
16 次查看(过去 30 天)
显示 更早的评论
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1193648/image.jpeg)
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1193653/image.jpeg)
Why does the function not able access the variables above?
0 个评论
采纳的回答
cr
2022-11-15
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
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!