Search code examples
matlabsymbolssymbolic-math

Classifying Symbolic Values and Symbolic Variables within a Symbolic Array


I have a vector of six values (but it can be infinitely long) of type "sym". In this case the vector has numbers and variables (all class sym).

a=[0.6 ; x_1; 0; 0; x_2; 0]

I want to write an algorithm that can tell if a(1)=number, a(1)=zero or, a(1)=variable.

But if x_1 and x_2 are symbolic variables then the array a and all of its elements are automatically symbolic, i.e., class(a(1)) will return 'sym' (from @horchler).


Solution

  • If x_1 and x_2 are symbolic variables then the array a and all of its elements are automatically symbolic, i.e., class(a(1)) will return 'sym'. It looks like you want to determine if an element is a symbolic value or a symbolic expression (made up of one or more symbolic variables). You can use symvar for this. You'll need to iterate through your array with a for loop to check each element, for example:

    syms x_1 x_2;
    a = [0.6; x_1; 0; 0; x_2; 0];
    
    for ai = vpa(a(:).')
        if isempty(symvar(ai))
            if ai == 0
                disp('Zero value');
            else
                disp('Non-zero value');
            end
        else
            disp('Symbolic expression or function');
        end
    end
    

    The vpa function is used to evaluate any expressions in a that might simplify to a numeric value. You can remove the vpa if you know what your input array looks like. You can use double to convert symbolic values to floating-point if desired.