How Can I replace the following for loop by vectorization?

Hi Guys,
I have a set of large sparse matrices:
W ,size=(1,10,m)
V ,size=(10,1,m)
Y ,size=(10,10,n)
and I need the output matrix P as follow:
P(i,j)=W(:,:,i)*Y(:,:,j)*V(:,:,i)
e.g if m=2 & n=3
P=[
W(:,:,1)*Y(:,:,1)*V(:,:,1) W(:,:,1)*Y(:,:,2)*V(:,:,1);
W(:,:,1)*Y(:,:,2)*V(:,:,1) W(:,:,2)*Y(:,:,2)*V(:,:,2);
W(:,:,1)*Y(:,:,3)*V(:,:,1) W(:,:,2)*Y(:,:,3)*V(:,:,2)
]
I want to see if you have any suggestion how to write this by a single line code. I have written the code with "two for loop" but because of the large size of matrices, it is almost slow. Any faster idea is really appreciated.
Thank you in advance,
Alireza

2 Kommentare

Jan
Jan am 22 Nov. 2016
Please post your code and typical input data. It matters if m=1e3 and n=1e7 or the other way around. Perhaps your code is slow due to a forgotten pre-allocation.
What does "sparse" mean? Do the arrays contain a lot of zeros or do you sue the type sparse, which does not work for 3D-arrays?
Actually, the size of matrices may be very large depend on the size of my problem, even 3000, and matrix Y is a sparse matrix, anyway we can ignore it now. As a simple example:
W(1,:)=[5 3 1];
W(2,:)=[0 1 4];
V(:,1)=[1;8;2];
V(:,2)=[6;4;7];
Y(:,:,1)=[3 1 5 ; 2 1 2 ; 0 3 1];
Y(:,:,2)=[5 0 2 ; 8 1 0 ; 2 3 7];
Y(:,:,3)=[7 0 4 ; 1 3 5 ; 7 2 0];
for i=1:2
for j=1:3
P(i,j) = ( ( (W(i,:))*Y(:,:,j)*V(:,i) ) );
end
end

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Roger Stafford
Roger Stafford am 23 Nov. 2016
Bearbeitet: Roger Stafford am 24 Nov. 2016
Here's a single line code, but I'm not sure it's faster than, or even as fast as, your two nested for-loop solution:
Corrected:
P = (reshape(repmat(W,10,1,1).*repmat(V,1,10,1),[],m)).*reshape(permute(Y,[2,1,3]),[],n);

5 Kommentare

would you update it for the example that I have added?
W(1,:)=[5 3 1];
W(2,:)=[0 1 4];
V(:,1)=[1;8;2];
V(:,2)=[6;4;7];
Y(:,:,1)=[3 1 5 ; 2 1 2 ; 0 3 1];
Y(:,:,2)=[5 0 2 ; 8 1 0 ; 2 3 7];
Y(:,:,3)=[7 0 4 ; 1 3 5 ; 7 2 0];
for i=1:2
for j=1:3
P(i,j) = ( ( (W(i,:))*Y(:,:,j)*V(:,i) ) );
end
end
I see I have made a mistake in my solution. It should have read:
P = (reshape(repmat(W,10,1,1).*repmat(V,1,10,1),[],m)).*reshape(permute(Y,[2,1,3]),[],n);
In your example in keeping with your original statement you ought to have:
W(1,:,1) = [5 3 1];
W(1,:,2) = [0 1 4];
V(:,1,1) = [1;8;2];
V(:,1,2) = [6;4;7];
Then my code would read:
P = (reshape(repmat(W,3,1,1).*repmat(V,1,3,1),[],2)).*reshape(permute(Y,[2,1,3]),[],3);
Thanks, great idea and also much faster than for loop :)
I'm glad to hear it. I was afraid it would be too slow. Sorry about the earlier error.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by