Different number of elements error.
1 回表示 (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Assembly についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!