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 Exchange에서 App 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