Rick T
Rick T

Reputation: 3389

multiplying arrays with different dimensions

I have two questions. How can I go about multiplying arrays with different dimensions?

Question 1 Example:

    A1=1,2,3,4,5,6
    A2=1,2,3
    The answer I would like to get would be
    A1*A2 =1,4,9,4,10,18

I was thinking of just using repmat but is this the best way?

Also

Question 2 Example:
A1=1,2,3,4,5,6,7  (notice the addition of another value the number 7)
A2=1,2,3
The answer I would like to get would be
A1*A2 =1,4,9,4,10,18,7 (notice the addition of another value the number 7)

I was thinking of for loops but the arrays are very large 500,000+ values and would take a long time to finish.

Is there a way to write some matlab/code that would work for both questions/examples?

Upvotes: 0

Views: 274

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112679

You can use mod to cycle through the elements of the shorter array:

result = A1.*A2(mod(0:numel(A1)-1,numel(A2))+1);

Or, if one length is an integer multiple of the other (first example), you can reshape the larger vector so that one dimension matches the shorter vector, and then use bsxfun:

result = bsxfun(@times, reshape(A1,numel(A2),[]), A2(:));
result = result(:).';

Upvotes: 2

Bitwise
Bitwise

Reputation: 7805

Here is an algebraic solution, if the size of A2'*A1 is reasonable:

B = spdiags(A2'*A1,0:numel(A2):numel(A1))
result = B(1:numel(A1))

Upvotes: 0

Related Questions