How can I add a value to my array?

조회 수: 2 (최근 30일)
Callum C
Callum C 2016년 3월 23일
답변: Ced 2016년 3월 23일
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