# Matlab A Q on multiplying two vectors

1. Mar 25, 2017

### loveinla

Hi--I have two vectors $x=(x_1, x_2, ..., x_n)$ and $y=(y_1, y_2, ..., y_n)$.

Now I want them to be multiplied in the following way:
for each $i=1,2,..,n$, I need $x_i*y_{i-1}-y_n$.

Can anyone help me on how to code this in Matlab?

BTW, I also want to input the length of the two vectors $n$ at the very beginning of the program. What do I need to do in order ensure the lengths of vectors $x$ and $y$ are the $n$ I specified as an input?

2. Mar 25, 2017

### Buzz Bloom

hi loveinla:

I don't know Matlab, but you will need to specify what happens for the special case i=1.

Good luck.

Regards,
Buzz

3. Mar 25, 2017

### Staff: Mentor

If you take advantage of the Matlab element wise multiply then you could simply write

Z= X.*Y

But that's not exactly what you want so instead shift the X right by one element by inserting a 0 element at the front and a 0 element at the end of Y so that they are now same length then use the elementwise multiply.

From there you can adjust the Z vector by dropping the first element and then add in the $Y_n$ term using an elementwise add.

Alternatively you could use a for loop and doing the computations in one pass but that's against the spirit of Matlab with its built in iteration feature and it's slower especially for long vectors.

4. Mar 25, 2017

### robphy

Here's an example that might be helpful:
Code (Text):

>>  A=[1 3 5 7 9]

A =

1     3     5     7     9

>> B=[2 4 6 8 10]

B =

2     4     6     8    10

>> A.*B

ans =

2    12    30    56    90

>> A(1:5).*B(1:5)

ans =

2    12    30    56    90

>> A(1:4).*B(1:4)

ans =

2    12    30    56

>> A(1:4).*B(2:5)

ans =

4    18    40    70

5. Mar 25, 2017

### loveinla

Thanks, it helps!