Asked by Tom
on 8 Jan 2012

can't do this

Hi, I'm attempting nested for loops and failing miserably.

Here's my code: -

close all;

clear all;

l=50;R=100;T=68;m=0.000125;w0=0.1;t=0;

mu=m/l;c=T/mu;

r=2;x0=l/r;

iter=1;

for x=1:33;

iter=1;

for n=1:5000;

wxt=((4*w0)/pi)*exp(-R*t)*((l/(pi*n^2*x0))*sin((n*pi*x0)/l)-(1/n)*cos((n*pi*x0)/l)+(l/(2*n*x0))*cos((n*pi*x0)/l))*sin((n*pi*x)/l)*cos((c*n*pi*t)/l);

wxtrec(iter)=wxt;

iter=iter+1;

end

w=sum(wxtrec)

wrec(iter)=w;

iter=iter+1;

end

plot(x,wrec)

For the first outer loop run (x=1), I want the inner loop to do 5000 circuits, then I want the sum of that result. Then I want it to go around again 5000 times for x=2, taking a sum of that result etc.

Once I have 33 summed results, I want to plot those sums against x

Answer by Walter Roberson
on 8 Jan 2012

Accepted Answer

With minimal changes. Improvements are possible.

close all;

clear all;

l=50;R=100;T=68;m=0.000125;w0=0.1;t=0;

mu=m/l;c=T/mu;

r=2;x0=l/r;

iter=1;

for x=1:33;

iter=1;

for n=1:5000;

wxt=((4*w0)/pi)*exp(-R*t)*((l/(pi*n^2*x0))*sin((n*pi*x0)/l)-(1/n)*cos((n*pi*x0)/l)+(l/(2*n*x0))*cos((n*pi*x0)/l))*sin((n*pi*x)/l)*cos((c*n*pi*t)/l);

%wxtrec(iter)=wxt;

wxtrec(n)=wxt; %NEW

iter=iter+1;

end

w=sum(wxtrec)

%wrec(iter)=w;

wrec(x)=w; %NEW AND IMPROVED

iter=iter+1;

end

plot(x,wrec)

Tom
on 9 Jan 2012

Walter Roberson
on 9 Jan 2012

Sorry, I had a typo which I have now corrected.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Image Analyst (view profile)

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/25602-can-t-do-this#comment_109074

Sign in to comment.