Error Code: Unable to perform assignment because the left and right sides have a different number of elements

11 次查看(过去 30 天)
Calculation of acceleration versus time using numerical derivatives
a=zeros(1,length(t)); % Create the velocity array - initially filled with zeros
a(1)=(v(2)-v(1))/(t(2)-t(1)); % first velocity point - method 1
a(2:end-1)=(v(3:end)-v(1:end-2))./(t(3:end)-t(1:end-2)); % method 3
Unable to perform assignment because the left and right sides have a different number of elements.
a(end)=(v(end)-v(end-1))./(t(end)-t(end-1)); % last point - method 2
  3 个评论
CECILIA
CECILIA 2023-9-12
They are the same and I plotted both the position graph and velocity graph on the same script just before so I don't understand why it's different.
Walter Roberson
Walter Roberson 2023-9-12
I suggest you use the debugger,
dbstop on error
and run the code. When it stops, examine the size() of each variable mentioned in the line, and examine the size() of the left-side expression and the size() of the right-side expression.
Your code would have a problem if v and t are the same size but different orientations. For example if v is a column vector when t is a row vector.

请先登录,再进行评论。

回答(1 个)

the cyclist
the cyclist 2023-9-12
编辑:the cyclist 2023-9-12
My best guess is that while your t and v have the same number of elements (which would allow plotting them against each other), one is a row vector while the other is a column vector.
For example, this code works:
N = 7;
t = rand(N,1);
v = rand(N,1);
a=zeros(1,length(t)); % Create the velocity array - initially filled with zeros
a(1)=(v(2)-v(1))/(t(2)-t(1)); % first velocity point - method 1
a(2:end-1)=(v(3:end)-v(1:end-2))./(t(3:end)-t(1:end-2)); % method 3
a(end)=(v(end)-v(end-1))./(t(end)-t(end-1)); % last point - method 2
but this code gives the error you got
N = 7;
t = rand(N,1);
v = rand(1,N);
a=zeros(1,length(t)); % Create the velocity array - initially filled with zeros
a(1)=(v(2)-v(1))/(t(2)-t(1)); % first velocity point - method 1
a(2:end-1)=(v(3:end)-v(1:end-2))./(t(3:end)-t(1:end-2)); % method 3
Unable to perform assignment because the left and right sides have a different number of elements.
a(end)=(v(end)-v(end-1))./(t(end)-t(end-1)); % last point - method 2

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by