Saving matrices inside a loop for each iteration
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Ted Shultz
2019-8-21
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)
3 个评论
Ted Shultz
2019-8-21
Do you really want to create a 5 dimensional variable that large? You are working with a very large number of values. Typically this would imply to me that you are either trying to save more information than intended, or you are solving a problem in a non-traditional way. You may want to step back and look at how you are trying to solve this.
If you are solving this the correct way, you may be able to save memory by using different types of variables rather than making everything a double. Or maybe you could use a bigger computer. But again, the approach I would take is go back and look at reworking the problem.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!