MATLAB: In an assignment A(I) = B, the number of elements in B and I must be the same.

ode45

In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in step (line 18) dy(3) = 0.1e1 / l ^ 2 / (-cos(y(2)) ^ ……
%% the main first function function xc = totalmotion (q1_0, q2_0, dq1_0, dq2_0) global_constants; global M; % hip mass global m; % foot mass global l; % leg length global r; % the slop angle
global g; % gravity acceleration global delta_t; % compute interval step global rad; rad = 180/pi; global Kp; % the proportional coefficient global Kd; % the differential coefficient global q2d; % the desired value of q2 tspan = [0:delta_t:2]; options = odeset('abstol',1e-13,'reltol',1e-13,'events',@collision); y0 = [q1_0 q2_0 dq1_0 dq2_0]; %%% initial state p(1) = M; p(2) = m; p(3) = r; p(4) = l; [t,y]=ode45(@step,tspan,y0,options,p);
n=length(t);
for i =1:n
q1 = y(i,1); q2 = y(i,2);
x_0 = 0;
y_0 = 0;
x1 = x_0;%%%%calculate the spacial positions of the links.
y1 = y_0;
xh = x1 + l * sin(-q1 + r);
yh = y1 + l * cos(-q1 + r);
x2 = double(-l * sin(-q2 - q1 + r) + x1 + l * sin(-q1 + r));
y2 = double(-l * cos(-q2 - q1 + r) + y1 + l * cos(-q1 + r));
xc = (M * (x1 + l * sin(-q1 + r)) + m * (-l * sin(-q2 - q1 + r) + x1 + l * sin(-q1 + r))) / (M + 0.2e1 * m);
end
end
%%% the second function function dy = step(t,y,p) M = p(1); m = p(2); r = p(3); l = p(4);
dy = zeros(4,1);
dy(1) = y(3);
dy(2) = y(4);
dy(3) = 0.1e1 / l ^ 2 / (-cos(y(2)) ^ 2 * m + M + m) * (-0.2e1 * sin(y(2)) * y(3) * y(4) * l ^ 2 * m - y(4) ^ 2 * sin(y(2)) * l ^ 2 * m - M * sin(-y(1) + r) * g * l - sin(-y(1) + r) * g * l * m + sin(-y(2) - y(1) + r) * m * g * l) + 0.1e1 / l ^ 2 * (cos(y(2)) - 0.1e1) / (-cos(y(2)) ^ 2 * m + M + m) * (Kp * (q2d - y(2)) - Kd * y(4) + sin(y(2)) * y(3) ^ 2 * l ^ 2 * m + sin(-y(2) - y(1) + r) * m * g * l);
dy(4) = 0.1e1 / l ^ 2 * (cos(y(2)) - 0.1e1) / (-cos(y(2)) ^ 2 * m + M + m) * (-0.2e1 * sin(y(2)) * y(3) * y(4) * l ^ 2 * m - y(4) ^ 2 * sin(y(2)) * l ^ 2 * m - M * sin(-y(1) + r) * g * l - sin(-y(1) + r) * g * l * m + sin(-y(2) - y(1) + r) * m * g * l) + 0.1e1 / l ^ 2 * (-0.2e1 * cos(y(2)) * m + M + 0.2e1 * m) / m / (-cos(y(2)) ^ 2 * m + M + m) * (Kp * (q2d - y(2)) - Kd * y(4) + sin(y(2)) * y(3) ^ 2 * l ^ 2 * m + sin(-y(2) - y(1) + r) * m * g * l);
end Thanks for your help.

Best Answer

I cannot follow what you are doing, and I cannot run your code.
However, the most likely problem is that you need to vectorize your code, since otherwise MATLAB will interpret multiply, divide, and exponentiation operations as matrix rather than element-wise array operations. That means using the ‘dot operator’, substituting ‘.*’ for ‘*’, ‘./’ for ‘/’, and ‘./’ for ‘^’.
Use the vectorize (link) fiunction, and see the documentation on Array vs. Matrix Operations (link) for details.