Speeding up the nested for loops

2 次查看(过去 30 天)
Hi,
I have a nested for loop that inside the innermost loop, the result of each iteration should be saved in a 4D matrix.
Althought the calculation is more accurate than curve fitting but the speed is awful. How can I speed up this piece of code? Parloop fails due to the way I save the data.
  9 个评论
Jan
Jan 2022-11-8
编辑:Jan 2022-11-8
We cannot run this code due to the missing input files. Then it is very hard to improve code, which is written as a large monolithic block, because we have to guess, where the bottleneck is.
Split the code into functions. Use a function as main part also instead of using the brute clearing header close all, clear,clc. Avoid clear of variabels, because this is usually (but not in all cases) a waste of time in Matlab.
Avoid the izterative growing of arrays, because this is very expensive:
NeededStim = zeros(SampN, ???); % Pre-allocate accordingly!!!
NeededChoice = zeros(SampN, ???); % Pre-allocate accordingly!!!
for N = 1 : SampN
SampleID = randsample([1:numel(SessID)],numel(SessID),true);
SampleStim = zeros(numel(SampleID), 250);
SampleChoice = zeros(numel(SampleID), 250);
for ss = 1 : numel(SampleID)
SampleStim(:, ss) = data(SessID(SampleID(ss)):SessID(SampleID(ss))+249,8);
SampleChoice(:, ss) = data(SessID(SampleID(ss)):SessID(SampleID(ss))+249,6);
end
NeededStim(N,:) = SampleStim(:);
NeededChoice(N,:) = SampleChoice(:);
end
This is ugly:
feval('assignin','base',name,Params)
Because this is a script, you create a variable dynamically in the local workspace. As eval this impedes Matlab's JIT acceleration drastically: Afterwards Matlab has to check the look-up table of variables instead of using efficient pointers to the values. This can slow down loops by a factor of 100. "Optimizing" this code is not the point inthis case, but cleaing it from evil pitfalls.
Zahra Yousefi Darani
Oh! Thanks for very constructive comments. I am going to rewrite the cod.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by