MATLAB: I have sym to double error in the loop.

doublesym

for i=1:njoint
q(:,:)=0
for j=1:2
for k=1:nelement
if elnode(k,j) == i
q(i,1) = q(i,1) - cc(k,j,1)
q(i,2) = q(i,2) - cc(k,j,2)
q(i,3) = q(i,3) - cc(k,j,3)
else
continue
end
end
end
q(i,1) = q(i,1) + ss(i,1) + jload(i,1)
q(i,2) = q(i,2) + ss(i,2)+ jload(i,2)
q(i,3) = q(i,3) + ss(i,3) + jload(i,3)
end
its my loop and ss matrix is a matrix with variable arrays. i want to create q matrix with ss matrix. i faced this error: The following error occurred converting from sym to double: DOUBLE cannot convert the input expression into a double array.
Error in analyze (line 96) q(i,1) = q(i,1) – cc(k,j,1)

Best Answer

Remember that the class of a variable is determined by the first assignment to the entire variable, so if q did not exist before, then the q(:,)=0 would make q into double because 0 is double. If cc contains symbolic variables then although q(i,1) - cc(k,j,1) would be symbolic, it would try to assign into the double q(i,1) which could fail if cc includes symbolic variables.
If your cc contains unresolved symbolic variables then you need your first assignment to q to be symbolic, such as
q = sym(zeros(njoint, 3));