How can I add a value to my array?

2 visualizzazioni (ultimi 30 giorni)
Callum C
Callum C il 23 Mar 2016
Risposto: Ced il 23 Mar 2016
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.

Risposta accettata

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

Più risposte (1)

Ced
Ced il 23 Mar 2016
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

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by