0

I'm trying to write some code in matlab that will manipulate each element in a vector and will also return a vector. So basically if I have a vector x = [1 2 3 4 5]'; I would like to perform 2 * x(i) * i, where i is the ith element in the vector. And return y = [2 8 18 32 50]';

Right now I have the code:

N = length(x);
for i=1:N
    y(i,:) = (i*2).*x(i,:);
end

I've new to Matlab so I've been doing research to try and learn the syntax that will let me do element by element multiplication and all that but it's been difficult. I can't get past that 1:numel(x) takes the place of my i. Again I'm new to matlab so any explanation on the answers that will help me learn is greatly appreciated. Thanks!

bla
  • 25,846
  • 10
  • 70
  • 101
user2743
  • 1,423
  • 3
  • 22
  • 34
  • A side note, it is best [not to use `i` as a variable name in Matlab](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab). – Shai Oct 16 '13 at 06:20

1 Answers1

2

Here is how to do it:

y = x.*(1:numel(x))*2

Here is why: Often we want to do an operation to every element in a vector or matrix. Matlab will allow you to do this with element-wise operations. For example, suppose you want to multiply each entry in vector x with its corresponding entry in vector y. In other words, x(1)*y(1), x(2)*y(2),etc. in order to do this, one should use the symbol . before the multiplication. In fact, you can put a . in front of any math symbol to tell Matlab that you want the operation to take place on each element of the vector or matrix.

bla
  • 25,846
  • 10
  • 70
  • 101