Multiply each item of an array with every item of another array

Dear matlab community,
I have a relatively simple problem:
I have two arrays, say:
1
2
3
and
10
11
12
I would like to multiply each of the first vector items with every of the second vector items, and print a new vector, which gives the output:
1*10
1*11
1*12
2*10
2*11
2*12
3*10
3*11
3*12
Thank you very much, I appreciate your help!
Greetings from Australia,
Chris

 Accepted Answer

Like this:
m1 = [1;2;3]
m2 = [10;11;12]
out = m1 * m2'
% Make into column vector
out = out(:)
I'm sure there are probably other ways.

5 Comments

Thank you very much! That works perfectly!
Do you happen to know how to the same with sums as well?
1
2
3
and
10
11
12
ans =
1+10
1+11
1+12
2+10
2+11
...
Many thanks!
Here's one way. You can replicate them to make 2D arrays and then do a simple addition:
m1 = [1;2;3]
m2 = [10;11;12]
m1a = repmat(m1', length(m1), 1)
m2a = repmat(m2, 1, length(m2))
out = m1a + m2a
% Make into column vector
out = out(:)
Thank you very much! It works perfectly again!
It seems like it is fairly easy to run out of memory when doing this with large arrays! I tried to do this with two 90k-long vectors! How much memory would be needed?
>> bytes = 90000*90000*8
bytes =
64800000000
>> gigaBytes = bytes / 1e9
gigaBytes =
64.8
And you'd have two arrays so that would be 129 GB. That's a fair amount. You probably don't have that much spare RAM.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!