1

Are there some nice way to do following.

I have 2 vectors where I want to only make sub vector multiplications. For examples,

a = 1:6;  b = (1:6)'

Then I'd like the result:

result = [1*1+2*2+3*3; 4*4+5*5+6*6] = [14; 77]

So, I'd like to multiply each sub vectors of 3 element with each others. In the end, last element of the vector result would then be the sum or the result of a*b

Thank you in advance for your help

etyM
  • 43
  • 1
  • 5

2 Answers2

2

maybe I'm missing something, but isn't it as simple as:

>> [a(1:3)*b(1:3) a(4:6)*b(4:6)]
ans =

   14   77

??

am304
  • 13,758
  • 2
  • 22
  • 40
2

This can be done as

sum(reshape(a,3,[]).*reshape(b,3,[])).'

or

dot(reshape(a,3,[]),reshape(b,3,[])).'
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Think `reshape(a,3,[])` would make more sense since question says `"sub vectors of 3 element"`. – Divakar Sep 26 '14 at 16:30
  • @Luis Mendo and @Divakar: THANKS! That was exactly what I was looking for. The two vectors have variable size and the same with the size of the sub vectors. As a note, you are the first where I see `.'` and not `'` when doing a transpose :-) – etyM Sep 27 '14 at 15:50
  • `'` is _conjugate_ transpose. About `.'` versus `'`, see [this very interesting Q&A](http://stackoverflow.com/q/25150027/2586922) – Luis Mendo Sep 27 '14 at 16:13
  • I know, but normally I only see people use `'`. However, I do not if the is a performance gain using `.'`, since flops is free :-) – etyM Sep 27 '14 at 16:31