Hello, Is there more vectorized way to write this code ? ( and avoid the loops)
for j=[1:size(C,1)];
for k=1:size(C,2)
C(j,k)=sum(sum(A([1:j],[1:k]).*B([j:-1:1],[k:-1:1])));
end
end
Thank you in advance
EDIT
I modified the code
j=1:size(C,1);
k=1:size(C,2);
B2=rot90(B,2);
C(j,k)=sum(sum(A(1:j,1:k).*B2(end+1-j:end,end+1-k:end)));
It's normal that I have the same value on all the matrix C ?
P.S: I understood that conv2 is the more performant function but I just want to understand where is the problem (why (j, k) doesn't vary) and what's the solution (without loop)

 採用された回答

Jan
Jan 2017 年 6 月 30 日
編集済み: Jan 2017 年 6 月 30 日

1 投票

Note: See https://www.mathworks.com/matlabcentral/answers/35676-why-not-use-square-brackets : Even omitting the unneeded square brackets will accelerate the copde already.
A = rand(56); % If I understand your inputs correctly:
B = rand(56);
tic;
for k = 1:100
C = zeros(size(A));
for j=[1:size(C,1)]
for k=1:size(C,2)
C(j,k)=sum(sum(A([1:j],[1:k]).*B([j:-1:1],[k:-1:1])));
end
end
end
toc
tic;
for k = 1:100
C = zeros(size(A));
for j=1:size(C,1)
for k=1:size(C,2)
C(j,k)=sum(sum(A(1:j,1:k).*B(j:-1:1,k:-1:1)));
end
end
end
tic
tic;
for k = 1:100
C = zeros(size(A));
for k = 1:size(C,2)
BB = B(end:-1:1, k:-1:1);
for j = 1:size(C,1)
C(j, k) = sum(sum(A(1:j, 1:k) .* BB(end-j+1:end, :)));
end
end
end
toc
Elapsed time is 5.530599 seconds.
Elapsed time is 4.280142 seconds.
Elapsed time is 3.919369 seconds.
I assume conv2 is a much better approach, although I cannot include the reverted parts of B yet.
But it is worth to know this detail in general: avoid unneeded square brackets. You see a corresponding MLint warning in the editor also: the small orange mark under the [.

2 件のコメント

term nv
term nv 2017 年 6 月 30 日
Interesting informations ! Thank you
term nv
term nv 2017 年 6 月 30 日
@Jan-Simon could you please see my EDIT ?

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

その他の回答 (1 件)

Honglei Chen
Honglei Chen 2017 年 6 月 30 日

2 投票

I don't know what dimensions you have in C, but this looks like
D = conv2(A,B);
Maybe you can use
D = D(1:size(C,1),1:size(C,2));
to extract the portions you want.
HTH

2 件のコメント

term nv
term nv 2017 年 6 月 30 日
Thank you for the answer.
If I perform a convolution for a matrix that size is (56,56) and a second one that has the same size, the size of convolution will be 56+56-1=111. But if I need only a portion (56,56), It wont be faster to calculate by the mathematic formula of convolution the result?
Stephen23
Stephen23 2017 年 6 月 30 日
"It wont be faster to calculate by the mathematic formula of convolution the result?"
Most likely conv2 would be faster, simpler, less buggy, more efficient,...

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

カテゴリ

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

製品

タグ

質問済み:

2017 年 6 月 30 日

コメント済み:

2017 年 6 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by