MATLAB: Variable changes to previously calculated value each iteration.

embedded for loopfor loop

Here is the equation I am dealing with
p2 = p1./(exp((50)./(29.3.*((T)))));
T = 1:340
p1 = 99977
I need to calculate p2 for all T values and have p1 change to the previously calculate p2 value each iteration.
I wrote this:
for i = 1:length(T)
p2(i) = p1./(exp((50)./(29.3.*((T)))));
p1 = p2(i)
end
I keep getting an error "Unable to perform assignment because the left and right sides have a different number of elements."
Do I need an embedded for loop to do this and if so, how so?

Best Answer

This is very easy with a preallocated vector (giving exactly the values as you stated here):
X = 100:440;
N = numel(X);
Z = nan(1,N);
Z(1) = 99977;
for k = 2:N
Z(k) = Z(k-1) ./ exp(50./(29.3*(X(1))));
end % ^ only use first X value.
Giving:
>> Z(:)
ans =
99977.00000
98285.38250
96622.38728
94987.53004
93380.33470
91800.33322
90247.06546
88720.07910
... lots of values here
340.39
334.63
328.97
323.41
317.93
312.55
307.27
302.07
But if you really want to use all of those X values (and not ignore them):
X = 100:440;
N = numel(X);
V = nan(1,N);
V(1) = 99977;
for k = 2:N
V(k) = V(k-1) ./ exp(50./(29.3*(X(k))));
end % ^ use each X value.
Giving:
>> V(:)
ans =
99977.00000
98301.99009
96671.05506
95082.62195
93535.18842
92027.31890
90557.64106
... lots of values here
8285.1
8252.5
8220.1
8188.0
8156.0
8124.2
8092.6
8061.2
8030.0