# Using the previous cumsum value of a for loop to calculate a new value

1 view (last 30 days)
DECLAN O RIORDAN on 26 Nov 2020
Commented: dpb on 26 Nov 2020
hi, i have a code in which in a for loop the cumulative sum of the equation needs to be used in the next loop and then put into another equation but i am having issues with matrix/array sizes.
This is my code:
A=9.41e-17;
n=5.5;
m=0.02;
B=1.054e-13;
phi=6.5;
x=4.44;
sigma=80;
%time stetup
timei=0;
timef=100;
dt=0.02;
timestep=(timef/dt)+1;
time=linspace(timei,timef,timestep);
for jj=1:timestep
if jj==0
w=0;
end
t=time(jj);
dw=B*(sigma/((1-w*(jj))^phi))*(t^m)*dt;
w=cumsum(dw);
de(jj)=(A*((sigma/((1-w))^n))*t^m*dt);
e=cumsum(de);
end
For this calculation the cumulative value of w has to be used to find the next change in w, the cumulative sum of w then has to be used to find the change in e and then the sumulative sum of e is then plotted against the time vector.
The issue i am having is when i create the vector dw by adding (jj) after it this error appears:
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To perform elementwise
matrix powers, use '.^'.
Error in TEST (line 33)
de(jj)=(A*((sigma/((1-w))^n))*t^m*dt);
if i use'.^' the matrix dimensions do not agree.

dpb on 26 Nov 2020
...
for jj=1:timestep
if jj==0
...
jj can never be zero...looks like you just need to initialize w to 0 before the loop begins, probably.
It would seem you don't need cumsum to build a vector but just sum(dw) for each step to use as the w for the next.
If you want to plot e as you go, do it then or save it in a vector for later, but each iteration is just a single value.
DECLAN O RIORDAN on 26 Nov 2020
sorry that jj should have been 1. i have now an issue of mismatched sized matrices as seen below dpb on 26 Nov 2020
You still don't need the if jj block in the loop; just initialize w before the loop begins.
And you reference (1-w) in the offending line, not w(jj) which is the new summation.