Different number of elements error.

조회 수: 1 (최근 30일)
Marios Christofides
Marios Christofides 2020년 7월 12일
답변: Star Strider 2020년 7월 12일
I'm trying to model the motion of a pendulum and in my code when I run it to display the different values, I get an error that it is "Unable to perform assignment because the left and right sides have a different number of elements." I haven't seen this error before and I don't understand whats wrong. Does anyone have any ideas?
theta0 = pi/3; g = 9.81; L = 1;
t = 0; tf = 20; dt = 0.005;
nt = (tf-t0)/dt;
t = linspace(t0,tf,nt);
theta = zeros(1,nt);
theta(1) = theta0;
omega = zeros(1,nt);
alpha = zeros(1,nt);
Etotal = zeros(1,nt);
H = L - L*cos(theta);
f = 'Time'; g = 'Omega'; h = 'Theta'; p = 'Alpha'; q = 'Energy';
fprintf('Time \t \t Omega\t \t Theta\t \t Alpha \t \t Energy\n',f, g, h, p, q)
fprintf('%5.2f \t %5.2f \t %5.2f \t %5.2f\n',t,omega,theta,alpha,Etotal);
while t <= 20
t = t + .5;
for k = 1:1:nt-1
omega(k+1) = -g/L*sin(theta(k))*dt + omega(k);
theta(k+1) = omega(k)*dt + theta(k);
alpha(k+1) = (omega(k+1) - omega(k))/dt;
Etotal = g*H + (1/2)*(L*omega)^2;
end
fprintf('%5.2f \t %5.2f \t %5.2f \t %5.2f\n',t,omega,theta,alpha,Etotal);
end

채택된 답변

Star Strider
Star Strider 2020년 7월 12일
Initially, you assign ‘g’ to the gravitational acceleration constant:
theta0 = pi/3; g = 9.81; L = 1;
then here you assign ‘g’ to the character vector ‘'Omega'’ that is a (1x5) character array:
f = 'Time'; g = 'Omega'; h = 'Theta'; p = 'Alpha'; q = 'Energy';
and that causes problems with ‘g’ in this line:
omega(k+1) = -g/L*sin(theta(k))*dt + omega(k);
that then throws the error and stops running the code.
If you correct that, by assigning ‘'Omega'’ to a different variable that is not used elsewhere in your code, you then encounter the problem with ‘^’ here because ‘omega’ is a vector:
Etotal = g*H + (1/2)*(L*omega)^2;
that you can correct by using element-wise exponentiation:
Etotal = g*H + (1/2)*(L*omega).^2;
I will let you do the necessary corrections.
.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by