Is there a way to simplify this expression?

1 次查看(过去 30 天)
Is there a way to simplify the following expression:
A=zeros(4);
B=zeros(4);
C=zeros(4);
d(i,j,1)=[0 1 0; 0 1 0; 1 1 1];
i=1:4;
j=1:4;
C(i,j,1)=A(i,j,1)+A(i,j,2); % <---- I think I can express that with sum (not sure how)
B(i,j,1)=convn(A(i,j,1),D,'same')+convn(A(i,j,2),D,'same'); % <--- convn can be replaced with conv2 or one convn expression

回答(1 个)

John D'Errico
John D'Errico 2016-5-16
编辑:John D'Errico 2016-5-16
But why bother to do so for the addition of two arrays? Be serious. Don't waste time trying to over optimize code that is trivial to write, to read, to use.
You cannot honestly think that sum will not be any faster than the basic addition of two numbers. Calling an extra function, that will require error checking, etc., will probably be slower, because of additional overhead.
You cannot think that using sum there will be more clear, more easily read. It is an addition of two numbers. What could be more clear than that?
So why do you want to do this? I suppose you could write it as:
C = A(:,:,1) + A(:,:,2);
or as
C = sum(A,3);
But why bother?
The same applies to the convn call. You already have something that was trivial to write. It would be no faster in some elegant version. Why waste time and mental energy worrying about how to make it run a milli-second more efficiently? Especially if that more elegant code might be harder to read?

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by