フィルターのクリア

Speeding up the nested for loops

3 ビュー (過去 30 日間)
Zahra Yousefi Darani
Zahra Yousefi Darani 2022 年 11 月 4 日
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
Zahra Yousefi Darani 2022 年 11 月 8 日
Oh! Thanks for very constructive comments. I am going to rewrite the cod.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by