t=zeros(1,4);
n=10000; % size of matrices
it=2; % average results over XX trails
for ii=1:it,
% random inputs
% John's rejected solution
tic;
n1=sum(diag(A*B'));
t(1)=t(1)+toc;
% element-wise solution
tic;
n2=sum(sum(A.*B));
t(2)=t(2)+toc;
% MOST efficient solution - using vector product
tic;
n3=A(:)'*B(:);
t(3)=t(3)+toc;
% using trace
tic;
n4=trace(A*B');
t(4)=t(4)+toc;
% make sure everything is correct
end;
t./it
dD16ZXJvcygxLDQpOwpuPTEwMDAwOyAlIHNpemUgb2YgbWF0cmljZXMKaXQ9MjsgJSBhdmVyYWdlIHJlc3VsdHMgb3ZlciBYWCB0cmFpbHMKZm9yIGlpPTE6aXQsIAogICAgJSByYW5kb20gaW5wdXRzCiAgICBBPXJhbmQobik7CiAgICBCPXJhbmQobik7IAogICAgJSBKb2huJ3MgcmVqZWN0ZWQgc29sdXRpb24KICAgIHRpYzsgCiAgICBuMT1zdW0oZGlhZyhBKkInKSk7CiAgICB0KDEpPXQoMSkrdG9jOwogICAgJSBlbGVtZW50LXdpc2Ugc29sdXRpb24KICAgIHRpYzsKICAgIG4yPXN1bShzdW0oQS4qQikpOwogICAgdCgyKT10KDIpK3RvYzsKICAgICUgTU9TVCBlZmZpY2llbnQgc29sdXRpb24gLSB1c2luZyB2ZWN0b3IgcHJvZHVjdAogICAgdGljOwogICAgbjM9QSg6KScqQig6KTsKICAgIHQoMyk9dCgzKSt0b2M7CiAgICAlIHVzaW5nIHRyYWNlCiAgICB0aWM7CiAgICBuND10cmFjZShBKkInKTsKICAgIHQoNCk9dCg0KSt0b2M7CiAgICAlIG1ha2Ugc3VyZSBldmVyeXRoaW5nIGlzIGNvcnJlY3QKICAgIGFzc2VydChhYnMobjEtbjIpPDFlLTggJiYgYWJzKG4zLW40KTwxZS04ICYmIGFicyhuMS1uNCk8MWUtOCk7CmVuZDsKdC4vaXQ=