# Saving matrices inside a loop for each iteration

4 views (last 30 days)
Jack Davies on 21 Aug 2019
Commented: Jack Davies on 21 Aug 2019
I have a loop of the form:
for i = 1: length(k)
for j = 1: length(A)
for m = 1: length(alpha)
if Top == 1
[M, N] = QG_Two_Layer_Matrix(Num, k(i), l, S, ...
beta, A(j), alpha(m), Top, U);
k_arr((i-1)*2*Num + 1 : i*2*Num, j, m) = k(i); % Array to store k values for each A and alpha
elseif Top == 2
[M, N] = QG_Two_Layer_Matrix(Num, k, l(i), S, ...
beta, A(j), alpha(m), Top, U);
k_arr((i-1)*2*Num + 1 : i*2*Num, j, m) = l(i);
end
[vec, lambda] = eig(M, N);
eig_func(i, j, m, :, :) = vec(:, :);
eig_freq((i - 1)*2*Num + 1 : i*2*Num, j, m) = diag(lambda);
max_growth(i, j, m) = max(imag(diag(lambda)));
end
end
end
The arrays eig_func and eig_freq are very large and so my code is very slow for Num > 64... How can one overcome this?
A is a 1 x 50 column vector, alpha is a 1 x 12 column vector and k = linspace(-Num/2, Num/2 - 1, Num).
##### 2 CommentsShowHide 1 older comment
Ted Shultz on 21 Aug 2019
If you highlight your code and click on the code icon, it is easier to read.

Ted Shultz on 21 Aug 2019
You are not preallocating those variables. If you do that, you will get a significant increase in speed. In some situations, I have had reductions in run times of several orders of magnitude.
To preallocate, just make the same variable before the loop starts of the size you expect it to be at the end (so it is filling in values rather than growing the matrix each loop)
Jack Davies on 21 Aug 2019