How to make the following matrix multiplication more efficient in Matlab?

I was interested to know if there is a way to make the following matrix multiplication more efficient, for example, vectorize it:

m=1000;n=500;
a=zeros(n,1);
b=rand(n,1);
A=rand(m,n);
B=rand(m,m);
for i=1:n
    a(i)=b'*(A'*B(i,:)'*B(i,:)*A)*b;
end

Thank you in advance

+4
source share
2 answers

You can significantly reduce the number of operations using associativity and transpose -product ::

t = B*A*b;
a = abs(t).^2;

, b'*(A'*B(i,:)'*B(i,:)*A)*b b'*A'*B(i,:)'*B(i,:)*A*b ( ), (B(i,:)*a*b)'*B(i,:)*A*b ( ); i (B*a*b)'*B*A*b.

, abs.

+3

B B' diag :

m=1000;n=500;
a=zeros(n,1);
b=rand(n,1);
A=rand(m,n);
B=rand(m,m);

%original for comparison
for i=1:n
    a(i)=b'*(A'*B(i,:)'*B(i,:)*A)*b;
end

%new version
%a2=diag(B*A*b*b'*A'*B');
%a2=a2(1:n); %emulate original cut-off

%new new version
a2=diag(B(1:n,:)*A*b*b'*A'*B(1:n,:)');

%compare difference
max(abs(a-a2)) %absolute error
max(abs(a-a2))./max(abs(a)) %relative error

rand():

>> max(abs(a-a2)) %absolute error

ans =

   8.1062e-06

, :

>> max(abs(a-a2))./max(abs(a)) %relative error

ans =

   1.9627e-15

, , , ,

b'*(A'*B(i,:)'*B(i,:)*A)*b

- , . ( B' B) 1, i. 1 x 1, . :

Tr (b' * A * Bi' * Bi * A * b) = Tr (Bi * A * b * b' * A * Bi')

Bi i - B. , , , . i

a(i)=B(i,:) * A * b * b' * A * B(i,:)';

, , (i,i) ()

B * A * b * b' * A * B'
+5

Source: https://habr.com/ru/post/1617088/


All Articles