Colon in MATLAB

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

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

I do not understand what he is actually doing. I know that w(1:5) quite a lot of iterating through the array w from the index from 1 to 5, but in the above statement, shouldn't all the indices of w be j(5) + k(5) at the end? Or am I completely wrong how this works? It would be great if someone posted the Java equivalent there. Thanks in advance: -)

0
source share
4 answers

I'm sure it means

"The first 5 elements of w should be the first 5 elements of j + the first 5 elements of k" (I'm 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 about โ€œadding a vectorโ€ here.

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

- the same as:

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

MATLAB uses vectors and matrices and is highly optimized for efficient operation management.

The expression w(1:5) means a vector consisting of the first 5 elements of w ; you add two 5 elementary vectors (the first 5 elements of j and k) and assign the result to the first five elements of w.

0
source

I think your problem is with what you call this statement. This is not an iteration, but a simple task. Now we only need to understand what was assigned.

I assume that j , k , w are all vectors 1 on N

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

Writing code using a colon notation makes it less verbose and more efficient. Therefore, it is highly recommended that you do this. In addition, the colon designation is the core and very powerful MATLAB function. Make sure you understand this well before moving on. MATLAB is very well documented, so you can read it here .

0
source

Source: https://habr.com/ru/post/907889/


All Articles