Optimizing: Getting rid of for loop

1 回表示 (過去 30 日間)
Raphaël
Raphaël 2017 年 12 月 5 日
編集済み: Matt J 2017 年 12 月 5 日
Hi, I've been scratching my head on this problem and keep seem to figureout a good way to do it.
I have a big matrix : size(A)=1024x1024x400 where the 3rd dimension is that of time and the two first of space. Here is an example of what I would want to do with it:
for x=1:1022
for y=1:1022
B(y,x,1) = mean2(A(y:y+2,x:x+2,1));
end
end
Doing it like that works but Matlab will do the calculations on one element at the time instead of all at the same time like in the following case:
B(:,:,1) = A(:,:,1).*A(:,:,2);
Is there a way to rewrite my initial code or use a function that would make it way faster? Thank you for any help.

採用された回答

Guillaume
Guillaume 2017 年 12 月 5 日
編集済み: Guillaume 2017 年 12 月 5 日
Not sure what the mean2d function do as it's not a standard matlab function. Assuming it's calculating a mean, then probably
kernel = ones(3, 3, size(A, 3));
kernel = kernel ./ numel(kernel); %convolution kernel for mean
B = convn(A, kernel, 'valid');
  2 件のコメント
Raphaël
Raphaël 2017 年 12 月 5 日
Yes it works thanks. One question, do you know the difference between conv2 and convn for this? Thanks
Matt J
Matt J 2017 年 12 月 5 日
編集済み: Matt J 2017 年 12 月 5 日
Because of the separable nature of the kernel, it may be more efficient to do this in separable passes,
B=convn(A,[1,1,1]/9, 'valid');
B=convn(B,[1;1;1],'valid');

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with Optimization Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by