Function with multiple outputs and FOR loop

3 views (last 30 days)
Sam
Sam on 22 Jul 2014
Answered: David Young on 22 Jul 2014
Hey fellas! Still new at this, thanks for the help.
I want five outputs which are the locations pos50,pos100,pos200,mu (mean at each location~3x2 vector),and sigma (variance at each location~3x2 vector).
function [pos50,pos100,pos200,mu,sigma]=assignment(dt)
dt=50,100,200; %distribution of particles at times 50,100,200 days
for t=1:dt:200 %time from day 1 to day 200
P=0.003/t; %initialize P
x=60; %centered at x=60 meters
y=165; %centered at y=165 meters
u=2*P*x; %velocity at location
v=-2*P*y; %velocity at location
x1=59+(60-59).*rand(10000,1); %initial position
y1=164+(166-164).*rand(10000,1); %initial position
D=0.001/t; %dispersion coefficient
E=randn(10000,1); %normally distributed random variables with zero mean and variance
N=randn(10000,1); %same as above
w=x1+u*dt+sqrt(2*D*dt*E); %particle transport equation
z=y1+u*dt+sqrt(2*D*dt*N); %particle transport equation
end
pos50=[w,z]; %position at day 50
pos100=[w,z]; %position at day 100
pos200=[w,z]; %position at day 200
figure, plot(w,z,'r+')
mu=mean(pos50,2)
sigma=var(pos50,0,2)
end
I want help figuring out how to get pos50,pos100,pos200,mu,sigma. Is how I set dt in the beginning correct?

Answers (1)

David Young
David Young on 22 Jul 2014
Note that each time
w = ...
is executed, the previous value of w is forgotten. So at the end of the for loop w and z hold the value that was computed last. Then the concatenation of w and z is assigned to each of pos50, po100 and pos200.
So what you need to do is assign to the output variables inside the loop. You'll need an if or switch to assign to the right one in each case. Alternatively, and more simply, you could put the three outputs into a vector rather than returning them as separate variables. That would bring many other advantages.
No, you're not doing the right thing at the start of the loop. Your assignment to dt isn't meaningful - the commas separate different statements. What you need is to assign a vector of the values:
dt = [50 100 200];
then loop over the values in the vector. Check the documentation for for to see how to do that - it's much simpler than what you have.

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!