Vectorize operations referencing adjacent elements of a matrix

I have made the simple code:
for i=2:xsize-1
for j=2:ysize-1
for n=2:zsize-1
matrix(i,j,n)=matrix(i,j,n)+0.2*(matrix(i,j,n)*6-matrix(i-1,j,n)-matrix(i+1,j,n)-matrix(i,j-1,n)-matrix(i,j+1,n)-matrix(i,j,n-1)-matrix(i,j,n+1));
end
end
end
This is part of a diffusion problem and it is particularly slow because the 3D matrix is large. Is it possible to vectorize an operation like this? How do you vectorize references to the matrix like this?

 採用された回答

Andrei Bobrov
Andrei Bobrov 2014 年 2 月 18 日
編集済み: Andrei Bobrov 2014 年 2 月 18 日

0 投票

out = convn(matrix,cat(3,[0 0 0;0 -1 0;0 0 0],...
[0 -1 0;-1 1 -1;0 -1 0],...
[0 0 0;0 -1 0;0 0 0]),'valid');

1 件のコメント

Christopher
Christopher 2014 年 2 月 19 日
編集済み: Christopher 2014 年 2 月 19 日
Thanks! This gives about a factor of 20 speedup. The form I used is
newmatrix = convn(matrix,cat(3,[0 0 0; 0 rt 0; 0 0 0],...
[0 rt 0; rt 1-rt*6 rt; 0 rt 0],...
[0 0 0; 0 rt 0; 0 0 0]),'same');
where rt=0.2

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeNumeric Types についてさらに検索

製品

タグ

質問済み:

2014 年 2 月 18 日

編集済み:

2014 年 2 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by