Error: Unable to perform assignment because left and right sides have a different number of elements
1 view (last 30 days)
Show older comments
Jacob Pesquera
on 2 Oct 2019
Commented: Walter Roberson
on 3 Oct 2019
I'm trying to plot a displacement vs. time graph for a simple harmonic oscillator showing different initial displacements to show the behavior of various amplitudes but my code keeps giving me the same error message: Error: Unable to perform assignment because left and right sides have a different number of elements and it specifies that the error is in line (23) but I don't know why it's giving me this error message? Here's my code:
12- N = 2500; %Discretizes time
13- delta_t = 0.04; %Time step in seconds (s)
14- v = zeros(N,1); %Initializes velocity
15- x = zeros(N,1); %Initializes displacement
16- t = zeros(N,1); %Initializes time
17- k = 1; %Spring constant for the mass-spring system
18- a = 1; %Exponential term that determines harmonicity or anharmonicity
20- %Define variables and initialize
22- delta_x_i = [2,5,10]; %Initial displacement vector in meters (m)
23- x(1) = delta_x_i; %First iteration for initial displacement
24- v_0 = 0; %Initial velocity in meters per second (m/s)
25- v(1) = [v_0,v_0,v_0]; %First iteration for velocity
26- t_0 = 0; %Initial time in seconds (s)
27- t(1) = t_0; %First iteration of time
29- for i=1:N-1 %A for-loop over all the timesteps
v(i+1) = v(i)-k*x(i)^a*delta_t;
x(i+1) = x(i)+v(i+1)*delta_t;
t(i+1) = t(i)+delta_t;
end
0 Comments
Accepted Answer
Walter Roberson
on 2 Oct 2019
delta_x_i = [2,5,10]
That is a vector of length 3
x(1) = delta_x_i
The left side names a scalar location that can hold only one value. The right side is a vector of length 3.
Hint:
x(1,:) = delta_x_i;
2 Comments
Walter Roberson
on 3 Oct 2019
You have an existing x variable that is interfering. This would not have happened if you used functions.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!