How to Multiply Two Vectors in MATLAB with Specific Conditions?

  • Context: MATLAB 
  • Thread starter Thread starter loveinla
  • Start date Start date
  • Tags Tags
    Vectors
loveinla
Messages
11
Reaction score
0
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?

Thanks in advance!
 
on Phys.org
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
 
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.
 
Here's an example that might be helpful:
Code:
>>  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
 
  • Like
Likes   Reactions: jedishrfu
jedishrfu said:
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.
Thanks, it helps!
 

Similar threads

  • · Replies 4 ·
Replies
4
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 5 ·
Replies
5
Views
4K