在MATLAB中绘图

时间:2017-03-16 04:41:01

标签: matlab plot ode

我有一个代码,我想在里面添加一个额外的情节。我想绘制两个函数的相对误差。我不确定在循环中放置它的位置,以便它不会给我一个错误消息并将所有三种情况绘制为单个图形。此外,我的相对错误代码可能有一些错误,这可能是导致问题的原因。

这是相对错误代码:

rel_error = (y_exact1 - Y(:,2)')./y_exact; %relative error 
figure()
plot(T,rel_error,'r')

这是我需要将其添加到

中的功能
function ivp1()
clear;clc;close all;
t=linspace(0,2.5);
K=[.02 .1 1.5];

for i=1:3
k =K(i);

[T,Y] = ode45(@prblm1_fun,t,0); %Solving for the approximate solution    to the IVP 

figure()
plot(T,Y)
hold on 

y_exact1 = 1/(k^2+pi^2)*(pi*exp(k*t)-pi*cos(pi*t)-k*sin(pi*t));
y_exact2 = 1/(2*k)*(exp(k*(t-1))-1) + pi/(k^2+pi^2)*(exp(k*t) + exp(k* (t-1)));
y_exact3 = 1/2/k*(exp(k*(t-1))-exp(k*(t-2))) + pi/(k^2+pi^2)*(exp(k*t) + exp(k*(t-1))) + 1/2/(k-1)*(exp(k*(t-2)) - exp(t-2));

for i=1:length(t)

if t(i)<1
plot(t(i),y_exact1(i),'mo')
hold on 

elseif t(i)<2
plot(t(i),y_exact2(i),'mo')
hold on

else
plot (t(i),y_exact3(i),'mo')
hold on

end
end
end
function dy= prblm1_fun(t,y) %This is the function of the IVP for     varying values of t 
dy = zeros(1,1); 
if t < 1
dy(1)= y(1)*k + sin(pi*t);
elseif t < 2
dy(1)= y(1)*k + 0.5;
else
dy(1)= y(1)*k + exp(t-2)/2;
end
end
end

这是k值之一的理想结果: Image 1

Image 2

1 个答案:

答案 0 :(得分:0)

两个错误的地方:

1)Y是来自100x1结果的ode45矩阵。尝试访问Y(:,2)会导致出现边界错误。

2)y_exact未定义。您只有y_exact1y_exact2y_exact3

示例代码:

function ivp1()
clear;clc;close all;
t=linspace(0,2.5);
K=[.02 .1 1.5];

for i=1:3
    k =K(i);

    [T,Y] = ode45(@prblm1_fun,t,0); %Solving for the approximate solution    to the IVP

    figure()
    plot(T,Y)
    hold on

    y_exact1 = 1/(k^2+pi^2)*(pi*exp(k*t)-pi*cos(pi*t)-k*sin(pi*t));
    y_exact2 = 1/(2*k)*(exp(k*(t-1))-1) + pi/(k^2+pi^2)*(exp(k*t) + exp(k* (t-1)));
    y_exact3 = 1/2/k*(exp(k*(t-1))-exp(k*(t-2))) + pi/(k^2+pi^2)*(exp(k*t) + exp(k*(t-1))) + 1/2/(k-1)*(exp(k*(t-2)) - exp(t-2));

    for j=1:length(t)
        if t(j)<1
            y_exact = y_exact1(j);
        elseif t(j)<2
            y_exact = y_exact2(j);
        else
            y_exact = y_exact3(j);
        end
        plot(t(j),y_exact,'mo')
    end
    rel_error = (y_exact1 - Y(:,1)')./y_exact; %relative error
    plot(T,rel_error,'r')
end
function dy= prblm1_fun(t,y) %This is the function of the IVP for     varying values of t
dy = zeros(1,1);
if t < 1
    dy(1)= y(1)*k + sin(pi*t);
elseif t < 2
    dy(1)= y(1)*k + 0.5;
else
    dy(1)= y(1)*k + exp(t-2)/2;
end
end
end

示例输出:

enter image description here