Cant create a function that return array correctly
7 views (last 30 days)
Show older comments
Hello,
I'm learning how to use Matlab for some computational physics simulations and i'm having the following problem.
I define a certain quantity
x = [0:dx:L];
y(1,:) = cos(x).*exp(-(x-1*L/2).^2/(2*20));
where the first index of the array represents time and the second (x) represents space.
I want to advance this quantity in time with a simple relation lets suppose, so i create a loop
for n = 1:Nmax
for i = 1:Imax
x(n+1,i) = x(n,i) - 0.5;
end
end
this work just fine..
But now imagine if i want to create a function that advances this quantity x in another .m file and i want to call it here as so
for n = 1:Nmax
x = advancex(n,Imax,x);
end
where the advance function (independent .m file)
function z =advancex(n,Imax,x)
for i = 1:Imax
z(n+1,i) = x-0.5;
end
This way work poorly because only final array is zero in all position in time except for the final position i.e. only z(Nmax,:) is correctly calculated.
How do I do this breakdown correctly in such a way as to end up with an array which has the values of z at every time step n in all positions?
Open to suggestions, thank you so much :)
0 Comments
Accepted Answer
dpb
on 18 Jun 2014
function z =advancex(n,Imax,x)
for i = 1:Imax
z(n+1,i) = x-0.5;
...only z(Nmax,:) is correctly calculated.
You don't have any thing except one n defined here in the function.
But, you don't really need a function or loops at all --
for n = 1:Nmax
for i = 1:Imax
x(n+1,i) = x(n,i) - 0.5;
end
end
Can be written as simply
x(2:Nmax+1,:)=x(1:Nmax,:)-0.5;
NB that x(1,:) is unchanged from original here and the final size(x,1) is one row larger than the original.
2 Comments
dpb
on 19 Jun 2014
It does; but--somewhere you have to allocate x to contain more than the one row n which your code doesn't show how/where you initialize it. When you write
x(n,:) = something;
where x isn't allocated or size(x,1)<n, then Matlab allocates an array of size(n,RHS) or reallocates (extends) to that size. But, any elements in x that have not been preassigned will be zero. I would expect that there is where the rest of the zeros are coming from.
Again I caution you that creating arrays dynamically this way is EXTREMELY expensive in run time performance and is NOT recommended.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!