Different number of elements error.
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Marios Christofides
am 12 Jul. 2020
Beantwortet: Star Strider
am 12 Jul. 2020
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 Kommentare
Akzeptierte Antwort
Star Strider
am 12 Jul. 2020
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Assembly finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!