matlabfor-loopmatrixsymbolic-mathsymengine

How can matrix be filled with symbolic expressions in Matlab?


I want to fill the rows of the matrix with symbolic expressions using for-loop. The code is given below.

for r=1:N
%dL/dfidot
frst(r)=diff(L,fidot(r));
%d/dt*dL/dfidot
dfrst(r)=diff(frst(r),fi(r))*fidot(r)+diff(frst(r),fidot(r))*fiddot(r);
%dL/dfi
scnd(r)=diff(L,fi(r));
%EQ of Motion 
EqofMotion(r)=dfrst(r)-scnd(r)==0;
acc(r)=solve(EqofMotion(r),fiddot(r));
C=zeros(N,1);
C(r,1)=acc(r);
end

acc is symbolic array, C is matrix. The idea is to fill r-th row of C matrix with acc(r) using loop. Program gives me an error as following:

The following error occurred converting from sym to double:
Error using symengine (line 58)
DOUBLE cannot convert the input expression into a double array.
If the input expression contains a symbolic variable, use VPA.

Error in Trying (line 56)
C(r,1)=acc(r);

How can I fix this problem?


Solution

  • You are trying to assign a symbolic value to a double array element. This is illegal because symbolic objects are not implicitly convertible to double. To solve this problem, you can make the C array an array of symbolic objects:

    C = sym(zeros(N,1)); % now C is an array containing the symbolic expressions 'zero' 
    C(r,1) = acc(r);