Clear Filters
Clear Filters

How to assign symbolic values to a 3D array in a for loop?

1 view (last 30 days)
I want to assign symbolic vallues of a 2D array to a 3D array in a for loop.
% % C = Coriolis(M,qdot,n)
% Returns Christoffels symbols build from
% - n = degrees of freedom (numeric. In this case n=6)
% - nxn matrix M (6x6 very complex symbolic matrix)
% - qdot (0x6 symbolic column vector)
function C = Coriolis(M,qdot,n)
C = sym(zeros(n,n));
c = sym(zeros(n,n,n));
dM = simplify(diff(M));
for i=1:n
for j=1:n
for k=1:n
c(i,j,k) = 0.5*(dM(i,j)+dM(i,k)-dM(k,j));
end
end
end
for i=1:n
C(:,i) = c(:,:,i)*qdot;
end
end
As you can see I want to increase the numeric variables i, j and k from 0 to n to create all possible combinations. I am sure this can be done in a more efficient way, but this is not the problem here. I was able to run this function correctly for the numeric version. The symbolic version triggers the following set of errors:
Error using sub2ind (line 52)
Out of range subscript.
Error in sym/subsref (line 766)
R_tilde = sub2ind(size(L), Idx.subs{:});
Error in Coriolis (line 12)
c(i,j,k) = 0.5*(dM(i,j)+dM(i,k)-dM(k,j));

Accepted Answer

Walter Roberson
Walter Roberson on 12 Oct 2015
You assume that your dM is n by n, but we do not at present have evidence that it is really that size. It would be more robust to extract the limits of the matrices by size(dM)
We also do not know for sure that M is symbolic; if it is numeric then diff(M) is not going to be the expected size. It is more robust to use the two-argument form of diff(), passing in the symbolic variable to be differentiated with respect to, so that you at least get an error message if M is not symbolic.
  4 Comments
Luc Ahrens
Luc Ahrens on 12 Oct 2015
I was able to debug everything. Some dimensions did indeed not match. Thank you.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!