Search code examples
matlabvectorsubstitutionsymbolic-math

MATLAB - subs method doesn't work on symbolic vector of indexed variables


Consider the following code:

A = sym('a', [1, 2]);
b = sym('b');
ans = A.^2 + b;
A = [1, 2];
b = 4;
subs(ans)

This yields the output

ans = [ a1^2 + 4, a2^2 + 4]

Whereas I would have wanted it to produce

ans = [ 5, 8]

What is required for the vector to be converted to numeric values aswell?


Solution

  • Here's a simpler solution:

    syms A b;        %Initializing symbolic variables
    expr = A^2 + b;  %Your expression (element-wise square is taken by default for sym class) 
    
    A = [1 2];   b=4;  %Assigning the values
    subs(expr)         %Substituting symbolic variables with corresponding assigned values  
    

    Output as desired:

    ans = 
    [ 5, 8]
    

    Comments:

    1. Always avoid dynamic variables. In your code, you're specifying A to be [1, 2] but your expression doesn't actually have A in it. It has a1 and a2 (and b obviously).
    2. Don't name your variables/functions after the reserved variable names or in-built functions. ans is used for the Most Recent Answer when expressions are not assigned to anything else. (That's why I replaced ans in your code with expr)