Variable changes to previously calculated value each iteration.

11 vues (au cours des 30 derniers jours)
Adam Kevin Francis Baker
Adam Kevin Francis Baker le 4 Mai 2019
Modifié(e) : Stephen23 le 4 Mai 2019
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?

Réponse acceptée

Stephen23
Stephen23 le 4 Mai 2019
Modifié(e) : Stephen23 le 4 Mai 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

Plus de réponses (1)

Erivelton Gualter
Erivelton Gualter le 4 Mai 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 commentaires
Erivelton Gualter
Erivelton Gualter le 4 Mai 2019
Hi Adam,
It does work as well.
Adam Kevin Francis Baker
Adam Kevin Francis Baker le 4 Mai 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by