Search code examples
matlabloopswhile-loopstore

Storing values with a while loop (matlab)


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.


Solution

  • 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.