Search code examples
matlabsymbolic-math

Create symbolic matrix with function elements


I'm trying to create a nxm matrix with elements that are functions of other symbolic variables (in this case the time t) with the following code:

syms t x(t) L
N = [                    0,                        0, ...
                         0,                        0;
                         0,                        0, ...
                         0,                        0;
 1 - 3*(x/L)^2 + 2*(x/L)^3, -x + 2*x^2/L - x^3/(L^2), ...
     3*(x/L)^2 - 2*(x/L)^3,        x^2/L - x^3/(L^2)];

The problem I have is that MATLAB converts the matrix N into a function, i.e. N(t). When I try to access a specific member

N(1, 1)

or submatrix

N(1, 3:4)

MATLAB trows the following error:

Symbolic function expected 1 inputs and received 2.

I understand the error message but it's not what I was expecting from the code. I dont want a symbolic matrix depending on t and I don't understand MATLABS behaviour in this case (for example why isn't N also a function of L or whatever). A solution is to create an zero symbolic matrix with

N = sym(zeros(3, 4));

and manually fill the elements

N(3, 1) = 1 - 3*(x/L)^2 + 2*(x/L)^3;
N(3, 2) = -x + 2*x^2/L - x^3/(L^2);
N(3, 3) = 3*(x/L)^2 - 2*(x/L)^3;
N(3, 4) = x^2/L - x^3/(L^2);

But as you can see this approach results in a lot of unecessary code. So, what is wrong with my first approach?


Solution

  • When you define x(t) it ends up as a symbolic function (symfun) instead of a symbolic object due to its dependency on t. This dependency is then carried over to your matrix N, making it a symbolic function dependent on t (which explains why it is only dependent on t and not L).

    >> syms t x(t) L
    >> N = ...
    >> whos
       Name      Size            Bytes  Class     Attributes
    
       L         1x1               112  sym                 
       t         1x1               112  sym                 
       x         1x1               112  symfun  
       N         1x1               112  symfun 
    

    You can avoid the automatic conversion to symfun by the workarounds you do above, or you can define it explicitly when you create you matrix N, like this:

    >> N = sym(char([    0,                        0, ...
                         0,                        0;
                         0,                        0, ...
                         0,                        0;
                         1 - 3*(x/L)^2 + 2*(x/L)^3, -x + 2*x^2/L - x^3/(L^2), ...
                         3*(x/L)^2 - 2*(x/L)^3,        x^2/L - x^3/(L^2)]));
    

    The trick here is the combined use of the sym() and char() functions. If you only use sym() without turning the matrix into a string it won't work.

    That being said, I personally find your second approach where you manually fill the elements to be more clear and easier to read.