Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

3-D dot product? 1

Status
Not open for further replies.

cah2oeng

Civil/Environmental
Feb 29, 2004
32
0
0
US
I'd like to multiply a 1-D vector by a 2-D array without using a loop. Here's what I currently have:

A = ones(10,10);
z = 1:10;
for i = 1:length(z)
result:),:,i) = z(i)*A;
end

Is there any way to do some sort of dot product between z and A that achieves the same result?

Thanks
 
Replies continue below

Recommended for you

dot product on the rows of A:
Code:
z.*A(i,:)

dot product on the columns of A:

Code:
z.*A(:,i)

If you want to keep z as a row/column vectorI think you will still need to loop, Although you could make a temporary variable that was padded with lots of z's...

Code:
ztemp=zeros(size(A))
ztemp(1:size(A,1),:) = z
result = z.*A

HTH



 
Here's the trick.
1. Make a 3d matrix where each page is a copy of the 2d matrix
2. Make a 3d matrix where each page is a 2d matrix filled with each value in z
3. Use ".*" to compute the product

This should be considerably quicker than the for loop for large z. Make it into a function if you are using it a lot.
Code:
% define the two operands 
A = rand(10,9);
z = [1:10];
n = length(z);
[A_rows, A_cols] = size(A);
% make a 3d version of z so that the values of z are along the 3rd dimension
z_3d = zeros(1,1,n);
z_3d(1,1,:) = z;
z_all = repmat(z_3d,[A_rows, A_cols, 1]);
% Make n copies of A in a 3d array;
A_all = repmat(A,1,1,n);
% compute the product
answer = A_all.*z_all;
M



--
Dr Michael F Platten
 
Good idea, Dr. Mike. Thanks for the help. Saves me MASSIVE computing time. Seems like the Mathworks guys would just make something like this a built-in function for us dummies. ;)
 
Status
Not open for further replies.
Back
Top