user692168
user692168

Reputation:

Understanding colon notation in MATLAB

So I'm completely new to MATLAB and I'm trying to understand colon notation within mathematical operations. So, in this book I found this statement:

w(1:5)=j(1:5) + k(1:5);

I do not understand what it really does. I know that w(1:5) is pretty much iterating through the w array from index 1 through 5, but in the statement above, shouldn't all indexes of w be equal to j(5) + k(5) in the end? Or am I completely wrong on how this works? It'd be awesome if someone posted the equivalent in Java to that up there. Thanks in advance :-)

Upvotes: 0

Views: 892

Answers (4)

Cubic
Cubic

Reputation: 15703

I am pretty sure this means

"The first 5 elements of w shall be the first 5 elements of j + the first 5 elements of k" (I am not sure if matlab arrays start with 0 or 1 though)

So:

w1 = j1+k1
w2 = j2+k2
w3 = j3+k3
w4 = j4+k4
w5 = j5+k5

Think "Vector addition" here.

Upvotes: 2

Roman Byshko
Roman Byshko

Reputation: 9052

I think your problem comes from the way how do you call this statement. It is not an iteration, but rather simple assignment. Now we only need to understand what was assigned to what.

I will assume j,k, w are all vectors 1 by N.

j(1:5) - means elements from 1 to 5 of the vector j
j(1:5) + k(1:5) - will result in elementwise sum of both operands
w(1:5) = ... - will assign the result again elementwise to w

Writing your code using colon notation makes it less verbose and more efficient. So it is highly recommended to do so. Also, colon notation is the basic and very powerful feature of MATLAB. Make sure you understand it well, before you move on. MATLAB is very well documented so you can read on this topic here.

Upvotes: 0

Jason S
Jason S

Reputation: 189866

MATLAB uses vectors and matrices, and is heavily optimized to handle operations on them efficiently.

The expression w(1:5) means a vector consisting of the first 5 elements of w; the expression you posted adds two 5 element vectors (the first 5 elements of j and k) and assigns the result to the first five elements of w.

Upvotes: 0

Oli
Oli

Reputation: 16065

w(1:5)=j(1:5) + k(1:5);

is the same that:

for i=1:5
   w(i)=j(i)+k(i);
end

Upvotes: 1

Related Questions