- Is really loop required?
- Can't it be vectorsed?
- Did you initialize the arrays filling in loop?
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
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!