MATLAB: Array size goes out of bounds in for loop.

array out of boundsfor loopmatrix array

I have multiple excel files which needs to be processed. There is a variable called SVD which comes inside a for loop whose limit extends from 1 to 4689, but the array size of SVD is 8214. The code runs for 3 or more files before showing the error.
<<

Best Answer

Preallocate! Preallocate! Preallocate! It makes your loops run faster and it avoids this sort of bugs.
What the problem is I suspect: You create or grow your SVD, SVDa and WVD in a loop, without preallocation, which means that a) they end up being row vectors when ideally they should be column vectors and b) their size never gets reset.
So, on the first step of your k987 loop, you end up with alt, PP, temps of a given size, e.g. 8214x1. Because, it's the first time you run your code SVD, SVDa and WVD don't exist and your loop slowly grows them until they are of size 1x8214. Concatenate the transpose and all is well.
Next step of the k987 loop (next excel file), alt, PP and temps are a different smaller size, e.g. 4629x1. SVD, SVDa and WVD and are already of size 8214x1 so your i and jy loop end up filling the first 4629 elements of each. Elements 4630:8214 are still there from the previous loop, so you end trying to concatenate 4629x1 with 8214x1. You get the error.
Had you preallocated SVD, SVDa and WVD, you wouldn't have had that problem. Before the loops:
SVD = zeros(size(alt), 'single');
SVDa = SVD;
WVD = SVD;
which also has the advantage of creating them as column vectors, meaning you don't need the transpose anymore.
Even better, get rid of the useless i and jy loop, create the vectors in one go which then does not need preallocation and ensure they're always the correct size:
SVD = polyval(temps, [1, 8.1847e-3, 0.032321, 5.018 + 3.1243e-4]); %you may have made an error in your original equation which I've not corrected here
SVDa = SVD / 100;
WVD = RH1/100 .* SVDa/1000;