Marion
Marion

Reputation: 319

For loop in Julia. Syntax confusion

I am a complete noob in Julia and its syntax. I am trying to follow this article on semi-definite-programming on Julia.

I would apprecieate if someone can help me figure out what the for loop in In[4] actually does:

for i in 1:m
A[:, (i-1)*n+1:i*n] .= random_mat_create(n)
b[i] = tr(A[:, (i-1)*n+1:i*n]*X_test)
end

To my understanding it should create a vector of matrices A (m of those) as well as an m-dimensional vector b. I am totally confused though on the indexing of A and the indexing of b.

I would like an explanation of the :, (i-1)*n+1:i*n part of this code. The reason I ask here is because I also dont know what to Google or what to search for in Julia documentation.

Upvotes: 3

Views: 497

Answers (2)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42264

There are two operations there that are not clear to you:

  • : operator. Consider a Matrix a = zeros(3,3). You could use array slicing operator (similarly to numpy or Matlab) to select the entire second columns as: a[1:end,2]. However, when selecting everything from start to the end those two values can be omitted and hence you can write a[:,2] (this always looked the easiest way for me to remember that)
  • . (dot) operator. Julia is very careful about what gets vectorized and what not. In numpy or R, vectorizing operations happens kind of always automatically. In Julia you have the control - but with the control comes the responsibility. Hence trying to assign values to the second column by writing a[:, 2] = 5.0 will throw an error because there is vector on the right and a scalar on the left. If you want to vectorize you need to tell that to Julia. Hence the dot operator .= means "perform element-wise assignment". Note that any Julia function or operator, even your own functions can be decorated by such dot .. Since this is a very important language feature have a look at https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting

Upvotes: 2

vin93843
vin93843

Reputation: 46

(i-1)*n+1:i*n creates a range from (i-1)*n + 1 to i*n. For example, if i=2 and n=10, this range becomes 11:20, so A[:, (i-1)*n+1:i*n] will grab all the rows of A (that's what : does), and columns 11-20.

Upvotes: 3

Related Questions