MATLAB: I am out of practice with MATLAB and I’m trying to get the sum from a loop to add itself to the sum of each iteration of the loop. I can accomplish by manually stepping the loop, but I know there must be an easier way. Can someone please help

looped summingrunning sumsummation

%Manual stepping of "loop"
clear
clc
h=input('What is height? ');
l=input('What is length? ');
w=input('What is frequency? ');
y=input('How many iterations? ');
x=0:0.001:l;
t=0;
F=(8*h)/(pi)^2;
n=1;
SUM=0
for n=1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S4=F*(S1*S2*S3);
SUM1=S4;
figure
plot(x,SUM1)
end
for n=n+1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S5=F*(S1*S2*S3);
SUM2=SUM1+S5
figure
plot(x,SUM2)
end
for n=n+1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S6=F*(S1*S2*S3);
SUM3=SUM2+S6
figure
plot(x,SUM3)
end
for n=n+1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S7=F*(S1*S2*S3);
SUM4=SUM3+S7
figure
plot(x,SUM4)
end
for n=n+1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S8=F*(S1*S2*S3);
SUM5=SUM4+S8
figure
plot(x,SUM5)
end
for n=n+1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S9=F*(S1*S2*S3);
SUM6=SUM5+S9
figure
plot(x,SUM6)
end
for n=n+1
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S10=F*(S1*S2*S3);
SUM7=SUM6+S10
figure
plot(x,SUM7)
end
%What I thought might shorten code
clear
clc
h=input('What is height? ');
l=input('What is length? ');
w=input('What is frequency? ');
y=input('How many iterations? ');
x=0:0.001:l;
t=0;
F=(8*h)/(pi)^2;
n=1:y;
for n=1:y
i=2*n-1;
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S4=F*(S1*S2*S3);
SUM=sum(S4, i);
figure
plot(x,SUM)
end

Best Answer

This is what it looks like you are trying to do to me
h=input('What is height? ');
l=input('What is length? ');
w=input('What is frequency? ');
y=input('How many iterations? ');
x=0:0.001:l;
t=0;%was this supposed to be a vector?
F=(8*h)/(pi)^2;
SUM = 0;
for n=1:y
i=2*n-1;
%%Update t here?
S1=((-1)^((i-1)/2))/(i^2);
S2=sin(i*pi*x/l);
S3=cos(w*t);
S4=F*(S1*S2*S3);
SUM = SUM + S4;
figure
plot(x,SUM)
title(['Plot of iteration ' num2str(i)])
end
Although you never modify t which will result in S3 always equaling 1, so maybe you meant to update t in the loop? Or did you mean to make t a vector like x?