Reputation: 63
I have a while loop and I've been unable to determine how to store the values successfully. Any help would be greatly appreciated.
n = 0; a = 21; b = 0; c = 0; y = 37.6991; T = 18.5; z = 0.1591; d = 0; f = 15.3049; q = 2.2391e4; e = 5; x = 60;
while n < x
a = a + b
c = y*(T-a)/z;
d = f*c;
b = d/q;
n = n + e;
end
The value I'm trying to store is a
, I can tell the values are correct inside the loop but just can't seem to store the values correctly.
Upvotes: 0
Views: 707
Reputation: 884
Another approach would be to recognise that it is a relatively simple recurrence relation:
n = 0; a = 21; y = 37.6991; T = 18.5; z = 0.1591; f = 15.3049; q = 2.2391e4; e = 5; x = 60;
while n < x
a(end+1) = a(end) + f * y * (T - a(end)) / (q * z);
n = n + e;
end
This calculation can also be vectorised, but if you want exactly the same output you need to be a little bit careful:
n = 5:5:55; y = 37.6991; T = 18.5; z = 0.1591; f = 15.3049; q = 2.2391e4; a0 = 21;
alpha = f * y * T / (q * z);
beta = (1 - f * y / (q * z)).^(0:length(n))
a = a0 * beta + alpha * [0 cumsum(beta(1:end-1))];
The code seems to lose clarity (to me) when vectorised, so I would probably prefer the loop in this scenario.
Upvotes: 1
Reputation: 927
Try this :
counter = 1;
n = 0; a = 21; b = 0; c = 0; y = 37.6991; T = 18.5; z = 0.1591; d = 0; f = 15.3049; q = 2.2391e4; e = 5; x = 60;
var = zeros(1,12);
while n < x
a = a + b;
c = y*(T-a)/z;
d = f*c;
b = d/q;
n = n + e;
var(counter) = a;
counter = counter+1;
end
I added a variable called var
which is a vector that stores the values of a
. In order t osave runtime i initialized it to the expected size of the variable var = zeros(1,12);
(This is not strictly required but is recommended.
Upvotes: 0