Array size goes out of bounds in for loop.

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

1 Comment

Check the sizes of alts, PP, temps and WVD1. The problem is here.

Sign in to comment.

 Accepted 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;

2 Comments

Thanks a ton mate.
The variable SVD instead of being nx1 matrix now is nx4 matrix. Any idea why?
Because I mistakenly inverted the order of the inputs. Should have been:
SVD = polyval([1, 8.1847e-3, 0.032321, 5.018 + 3.1243e-4], temps);
Or you coud write the polynomial explicitly:
SVD = 5.018 + 0.032321*temps + 8.1847e-3*temps.^2 + 3.1243e-4 + temps.^3;
Note that in both cases I've kept your 3.1243e-4 + temps.^3 as you initially wrote it. I suspect it should have been 3.1243e-4 * temps.^3 instead.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!