Search code examples
matlabfluid-dynamics

About symbolic MATLAB


What is wrong with the following code?

clear all

syms x y a ;

u=2*x*y;
v=a^2+x^2-y^2;

diff=diff(u,'x',1)+diff(v,'y',1);
if diff==0
    disp('Liquid motion is possible.')
    disp('Stream function exists.')
else
    disp('Liquid motion is not possible.')
    disp('Stream function does not exist.')
end

diff2=diff(v,'x',1)-diff(u,'y',1);
if diff2==0
    disp('Velocity potential exists.')
else
    disp('Velocity potential does not exist.')
end

This comes in the command window when I run the above.

Liquid motion is possible.
Stream function exists.
Error using sym/subsindex (line 672)
Invalid indexing or function definition. When defining a function, ensure that the body of the function is a SYM
object. When indexing, the input must be numeric, logical or ':'.

Error in sym>privformat (line 1502)
    x = subsindex(x)+1;

Error in sym/subsref (line 694)
            [inds{k},refs{k}] = privformat(inds{k});

Error in q7 (line 17)
diff2=diff(v,'x',1)-diff(u,'y',1);

But if I rewrite(redefine) the symbolic variables after the first if construct, it runs fine. Also if I cancel the first if construct, it runs.


Solution

  • I would avoid to overwrite a reserved name, so instead of

    diff=diff(u,'x',1)+diff(v,'y',1);
    

    I would suggest

    derFcn = diff(u,'x',1)+diff(v,'y',1);
    

    This triggers the second error;

    diff2=diff(v,'x',1)-diff(u,'y',1);
    

    at this point diff is your diff value (which, incidentally is 0) so it is equivalent to write

    0(v,'x',1)
    

    which, of course, will not compile and it is not what you meant.

    So, please, make the substitution (and update your if statements accordingly).