0

(Just approaching Matlab for personal understanding), suppose I have a Z,Y matrix in this case Z=1 Y=3

A=1:3

output: 1 2 3

Now I need to increase the matrix vertically to obtain:

1 2 3
2 4 6
3 6 9

How can I achieve that without using a loop?

FeliceM
  • 4,163
  • 9
  • 48
  • 75

2 Answers2

4

The easiest way is to use vector multiplication.

If your goal is to obtain

1 2 3
2 4 6
3 6 9

given A=1:3

all you have to do is

A.'*A

This will take the vector product of the transpose (.') of A with A itself

Federico
  • 1,092
  • 3
  • 16
  • 36
  • Thanks a lot. Appreciated. – FeliceM Apr 24 '15 at 13:30
  • 1
    well you explicitly wrote **transpose** - the transpose operator is `.'` - the `'` is the conjugate transpose. Though it doesn't matter in this case, its not entirely correct as it stands. [**It is just a matter of clean programming**](http://stackoverflow.com/questions/25150027/using-transpose-versus-ctranspose-in-matlab). – Robert Seifert Apr 26 '15 at 12:15
  • 1
    @thewaywewalk then please accept my apologies, I never seen that difference. reinstating your edit. – Federico Apr 26 '15 at 12:22
2

Another way is to use bsxfun:

A = [1 2 3];
B = bsxfun(@times, A.', A);

This is essentially the same answer as Federico's where the outer product of the vector is taken.

rayryeng
  • 102,964
  • 22
  • 184
  • 193