Variable changes to previously calculated value each iteration.

27 views (last 30 days)
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?

Accepted Answer

Stephen
Stephen on 4 May 2019
Edited: Stephen on 4 May 2019
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

More Answers (1)

Erivelton Gualter
Erivelton Gualter on 4 May 2019
Since T is an array and you are using a for loop to find each value of p2(T), you should you T(i) instead of T.
Check the correct code:
clear all
T = 1:340;
p1 = 99977;
for i = 1:length(T)
p2(i) = p1/(exp(50/(29.3*T(i))));
p1 = p2(i);
end
plot(T, p2);
I am also plotting the P2 vs T for further verification.
  3 Comments
Adam Kevin Francis Baker
Adam Kevin Francis Baker on 4 May 2019
I think I asked this question wrong. I submitted another question to ask what I really needed and can't figure out how to delete this question. I think you answered the question I asked. I meant to ask this question.
I would like to thank you for your time and effort...sorry I'm not proficient in matlab/the matlab website.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!