Why is the hold on function causing 3 graphs?

clc%clears screen
clear all%clears history
close all%closes all files
format long
k=7.13*10^3;
alpha=0.001;
beta=0.0041;
f=@(t,x) k*(alpha-x).^2.*(beta-x/2);
prev=0;
h=10;
while(1)
[t,x]=kutta(f,[0,10],0,h);
if(abs(x(end)-prev)/abs(prev)<0.000001)
break;
end
h=h/10;
prev=x(end);
end
disp('Approximate x(10) is');
disp(x(end));
disp('The value of h is')
disp(h)
plot(t,x,'b')
function [x,y]=kutta(f,tspan,y0,h)
x = tspan(1):h:tspan(2); % Calculates upto y(3)
y = zeros(length(x),1);
y(1,:) = y0; % initial condition
for i=1:(length(x)-1) % calculation loop
k_1 = f(x(i),y(i,:));
k_2 = f(x(i)+0.5*h,y(i,:)+0.5*h*k_1);
k_3 = f((x(i)+0.5*h),(y(i,:)+0.5*h*k_2));
k_4 = f((x(i)+h),(y(i,:)+k_3*h));
y(i+1,:) = y(i,:) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h; % main equation
end
hold on
plot(x,y,'r')
legend('Exact','Kutta')
end
Whenever I run this 3 graphs appear. I do not want the straight line one and dont know where im mesing up at. Please help.

2 Kommentare

KSSV
KSSV am 17 Mär. 2020
Remove the plot inside the function. You are plotting inside the function also.
Daniel Hein
Daniel Hein am 17 Mär. 2020
What do you mean? If i remove the plot function outside of the function the code wont run. unless im misunderstood what you meant.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Mahesh Taparia
Mahesh Taparia am 20 Mär. 2020

0 Stimmen

Hi
Based on the parameters you have specified, the function kutta has been called for three times which resuls in 3 plots inside the function (2 with same curve) and one plot is because of last line of the main code. For better understanding apply break point in the loop and analyze the plot.

Kategorien

Mehr zu Graphics finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 17 Mär. 2020

Beantwortet:

am 20 Mär. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by