Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab A Q on multiplying two vectors

  1. Mar 25, 2017 #1
    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!
     
  2. jcsd
  3. Mar 25, 2017 #2
    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
     
  4. Mar 25, 2017 #3

    jedishrfu

    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.
     
  5. Mar 25, 2017 #4

    robphy

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member

    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
     
     
  6. Mar 25, 2017 #5
    Thanks, it helps!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: A Q on multiplying two vectors
Loading...