Error using plot Vectors must be the same length.
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Every time I run this code, I get "Error using plot Vectors must be the same length.
function f = lab_8( x , y)
f = ((x.^2)*cos(y) + 0.1);
end
function [x,y] = lab_8_method_2(f, y0, sp, h)
x = sp(1):h:sp(2);
y = y0;
for n =1:length(x)-1
x(n) = (n-1)*h;
y(n+1) = y(n)+h*(0.75*f(x(n),y(n))+...
0.25*f(x(n)+h/0.5,y(n)+...
(h/0.5)*f(x(n),y(n))));
end
end
function [x,y] = lab_8_method_4(f, y0, sp, h)
x = sp(1):h:sp(2);
y = y0;
for n=1:length(x)-1
k1=f(x(n) , y(n));
k2=f(x(n)+h/2 , y(n)+h*k1/2);
k3=f(x(n)+h/2 , y(n)+h*k2/2);
k4=f(x(n)+h , y(n)+h*k3);
dy= h*(k1+2*k2+2*k3+k4) / 6;
y(n+1) = y(n) + dy;
end
end
[x, y2] = lab_8_method_2(@lab_8, 0.3, [0 1 ], 0.01);
plot(x, y2 ,'r'); hold on;
[x, y4] = lab_8_method_4(@lab_8, 0.3, [0 1], 0.01);
plot(x, y4, 'b'); hold on;
qn = dsolve('Dy = (x.^2)*cos(y) + 0.1', 'y(0) = 0.3');
syms t
v = subs(qn, [t], [x]);
a = eval(v); plot(x,a,'y'); hold off;
legend('2-го порядку', ' 4-го порядку', ' Точна відповідь');
T=table(x(:), y2(:), y4(:), a(:));
T.Properties.variableNames = {'xi','Рунге-Кутта 2-го порядку','Рунге-Кутта 4-го порядку', 'Точна відпоівдь'}
1 comentario
Image Analyst
el 14 de Nov. de 2022
Please put only one line of code on a line and then highlight your code and click the Code icon to format your code as code so we can read it easily and copy it easily (to run it in MATLAB).
Respuestas (1)
Jan
el 14 de Nov. de 2022
[x, y2] = lab_8_method_2(@lab_8, 0.3, [0 1], 0.01);
plot(x, y2 ,'r'); hold on;
[x, y4] = lab_8_method_4(@lab_8, 0.3, [0 1], 0.01);
plot(x, y4, 'bo'); hold on;
qn = dsolve('Dy = (x.^2)*cos(y) + 0.1', 'y(0) = 0.3');
Consider this warning.
syms t
v = subs(qn, t, x);
a = eval(v);
size(x)
size(a)
This is the problem. x is a row vector with 101 elements. The equation is defined as CHAR vector. t is symbolic, but you substitute it by a numerical vector. The equation does not contain a "t", but only y and x, so substituting t is not meaningful.
plot(x,a,'y'); hold off;
function f = lab_8(x , y)
f = x.^2 * cos(y) + 0.1;
end
function [x,y] = lab_8_method_2(f, y0, sp, h)
x = sp(1):h:sp(2);
y = y0;
for n = 1:length(x)-1
x(n) = (n-1)*h;
y(n+1) = y(n)+h*(0.75*f(x(n),y(n))+...
0.25*f(x(n)+h/0.5,y(n)+...
(h/0.5)*f(x(n),y(n))));
end
end
function [x,y] = lab_8_method_4(f, y0, sp, h)
x = sp(1):h:sp(2);
y = y0;
for n=1:length(x)-1
k1 = f(x(n) , y(n));
k2 = f(x(n)+h/2 , y(n)+h*k1/2);
k3 = f(x(n)+h/2 , y(n)+h*k2/2);
k4 = f(x(n)+h , y(n)+h*k3);
dy = h*(k1+2*k2+2*k3+k4) / 6;
y(n+1) = y(n) + dy;
end
end
0 comentarios
Ver también
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
