matlabplotsymbolic-mathfunction-handle

Issue with using fplot on a symbolic expression


Here is an example where fplot doesn't plot anything:

a=0.336;
Ta=9.476;
Te=1.208;
Tw=1.498;
eqh=[0.661;0.619;0.568];
ex=[-1.24;-1.346;-1.441];
en=-ex;
ey=[0.376;0.705;0.968];
eqx=[-0.309;-0.357;-0.392];
eh=[1.594;1.583;1.545];
eyqh=[0.642;0.78;0.897];
a0=a*Ta*Te^2;
syms bt Td Ki Kp;
a1=sym([]);a2=sym([]);a3=sym([]);a4=sym([]);exqh=sym([]);

for i=1:3
        Kp=1/bt;
        exqh(i)=en(i)*eqh(i)+eqx(i)*eh(i);
        Ki=1/(bt*Td);
        a1(i)=Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp;
        a2(i)=a*Te^2*ey(i)*Ki+Ta+Tw*exqh(i)-eyqh(i)*Kp*Tw;
        a3(i)=en(i)+ey(i)*Kp-eyqh(i)*Ki*Tw;
        a4(i)=ey(i)*Ki;
        assume(bt~=0)
        f=@(bt) a1(i)
        fplot(f,[0.01 1],'b')
        hold on
end

And here is another example, where fplot works:

syms y x;
y=@(x) 2/x+6;
z=y;
assume(x~=0)
fplot(z,[-1 1],'b')

I cannot understand the difference between these two cases. In my opinion, they are the same.

Would anyone please explain why the top example doesn't work, but the bottom one does?


Solution

  • fplot requires an expression that returns a numeric value. f returns a sym (symbolic expression), so it doesn't work, whereas z returns a number - so it does. That's all the difference.

    Note that in the working example, you overwrote the y sym on the 2nd row, which means you provided a "proper" function handle to fplot, "by mistake". In fact, you need much less code for that example to work:

    fplot( @(x)2./x+6, [-1 1], 'b');
    

    The easiest way to get the top code working is by using matlabFunction. In other words, you can fix your code by changing this line:

    f=@(bt) a1(i)
    

    to this:

    f = matlabFunction(a1(i));