How can I add a value to my array?

1 次查看(过去 30 天)
This is the Forward Euler script:
y=input('initial value of y: ');
x=input('initial value of x: ');
h=input('value of h: ');
xmax=input('value of xmax: ');
while x<xmax
n=n+1;
y=y+h*fun(x,y); %apply Forward Euler to y
x=x+h; %update value of x
truth=exp(-0.5*x^2); %true value of y
diff=abs(truth-y); %difference between truth and estimate
xx(n)=x;
yy(n)=y;
disp([x,y,diff]);
plot(xx,yy);
end
I have the initial conditions such that y(0)=1, however I can't figure out how to add this information into the two arrays xx and yy, such that the graph begins at x=0, rather than x=0.1.
Thanks.

采纳的回答

Walter Roberson
Walter Roberson 2016-3-23
Before the "while",
xx(1) = x;
yy(1) = y;
n = 1;

更多回答(1 个)

Ced
Ced 2016-3-23
To answer your question, you could just concatenate them, e.g.
x = [ 2 3 ];
% now add a 1:
x = [ 1 x ];
BUT The better way of solving your problem is the following:
1. determine how many time steps you will have (which you know, since you have xmax and h), e.g.
Nt = ...
2. preallocate the full vectors, i.e.
xx = zeros(Nt,1);
yy = zeros(Nt,1);
3. Include your initial condition right there
xx(1) = ...
yy(1) = ...
3. use a for loop instead of while
for i = 2:Nt
xx(i) = xx(i-1) + h;
yy(i) = yy(i-1) + ...
plot(xx(1:i),...)
end
As a side note, you actually know the whole vector xx beforehand, no need to "update it" in each loop iteration.
Hope this helps.
Cheers

类别

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