0

I am trying to use the while loop function in Matlab but have been met with the error "Index exceeds the number of array elements (1)". How can I fix this? My code is pasted below:

clear all
clc

% Defining variables
alpha=0.047;% growth rate
dt=1; % timestep of 1 second
Tatm=293.15; % atm temperature, deg Kelvin. (20 deg Celsius + 273.15)
A=20; % Area = 4m x 5m
MW=28.97;% Molecular weight of air in g/mol
P=101325; % atmospheric pressure in pascals
R=8.314; % J/kg/Kelvin
Cp=1000; % Specific Heat Capacity of air J/kg
Mu0=0;% mass entrained in upper layer initial
Mp=0; % mass entrained in plume
H=5; % height of compartment 

z(1)=5;
t(1)=1;
T(1)=293.15;
m(1)=0;
k=1;

while z(k)>0
    Q=0.7*alpha*t^(2);
    Mp=0.076*(Q^(1/3))*(5^(5/3));
    Tp=(Q/(Mp*Cp))+293.15;
    m(k)=m(1)+Mp*dt;
    T(k)=((m(1)*T(1))+(Mp*Tp*dt))/m;
    p=(P*MW)/(R*T(1));
    V=m(k)/p;
    deltaz=(V/A);
    z(k)=z(1)-deltaz;
    k=k+1;
end

Thanks!

  • The line `z(1)=5;` creates a vector of length 1. On the 2nd iteration of the while loop, `k` will have a value of 2, so `z(k)=z(1)-deltaz;` attempts to write to `z(2)`, which exceeds the length of `z`. One option could be to allow `z` to grow inside the loop: `z = [z; z(1)-deltaz];`. This causes a lot of memory reallocations, so is computationally inefficient, but should prevent the error you asked about. – Harry Apr 07 '21 at 22:29
  • @Harry: indexing out of bounds for writing is allowed. In fact, `z(end+1)=0` is a much more efficient way to grow the array than `z=[z;1]`. https://stackoverflow.com/a/48353598/7328782 – Cris Luengo Apr 08 '21 at 00:19
  • What is happening is that `while z(k)>0` indexes out of bounds on the 2nd iteration. Here we are not writing, but reading a value that doesn’t exist. – Cris Luengo Apr 08 '21 at 00:20
  • The solution probably is to increment `z` before the assignment to `z(k)`, swapping the two last lines of the loop. – Cris Luengo Apr 08 '21 at 00:21

0 Answers0