Fast computation of an equation.

Given two matrices:
We want a the fastest way to compute the vector \phi.... (j=1 to m).
Is there a way to use parallel computation, any trick?

8 Comments

What does it mean ?
As then is a vector and would be the ith element of vector
If you arrange Y and Z as 2D array
so that varying i in is traveling along rows, then from R2019a onwards,
sum((x-Y).*(Z-x), 2)
+1 on Walter's solution. You probably want to write
"then from R2016b onwards".
I probably organize data in transpose way, but this does not have huge impact.
Not sure if the computation is to do once or multiple times with Y/Z fix or x fix.
function Z = quad_trans(X,W,V)
% X is a matrix n by s
% W and V are matrices m by n
N = size(X,2);
Z=zeros(size(W,1),N);
for i=1:N
Z(:,i)=sum((X'- W).*(V-X'),2);
end
end
Well, I modified a little bit the statement.
Thanks for the observation Bruno Luong.
Walter, We currently are computing the solution that way. But I think we are not taking advantage of parallelism or other faster matlab characteristics.
Bruno is right, I should have said R2016b onwards.
I see that you extended by a dimension. The code remains the same provided that you arrange the so that the k run along the third dimension, so being MATLAB's x(1,i,k) . The result would be m (length of j) by 1 by s (length of k), which you might want to squeeze() to a 2D array.
Thanks Walter! Is working.
Bruno Luong
Bruno Luong on 10 Sep 2019
Edited: Bruno Luong on 10 Sep 2019
what are typically m,n and s?
If you have X as matrix the best method might be different, see my answer bellow.

Sign in to comment.

 Accepted Answer

Bruno Luong
Bruno Luong on 10 Sep 2019
Edited: Bruno Luong on 10 Sep 2019
The efficientcy of the bellow method depend on m, n, s
% Generate dummy test data
m = 1000;
n = 1000;
s = 1000;
W = rand(m,n);
V = rand(m,n);
X = rand(n,s);
% Walter method
tic
Xp = permute(X,[3 1 2]);
Z1 = sum((Xp-W).*(V-Xp),2);
Z1 = reshape(Z1,[m s]).';
toc % Elapsed time is 2.816333 seconds.
% My new method
tic
Z2 = -sum(X.^2,1)+(W+V)*X-sum(W.*V,2);
Z2 = Z2.';
toc % Elapsed time is 0.040274 seconds.
% Check correctness
norm(Z1-Z2,'fro')/norm(Z1,'fro') % 4.6622e-15

More Answers (0)

Community Treasure Hunt

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

Start Hunting!