[英]For loop in Julia. Syntax confusion
I am a complete noob in Julia and its syntax.我是 Julia 及其语法的完整菜鸟。 I am trying to follow this article on semi-definite-programming on Julia.
我正在尝试在 Julia 上关注这篇关于半定编程的文章。
I would apprecieate if someone can help me figure out what the for loop in In[4]
actually does:如果有人可以帮助我弄清楚
In[4]
中的 for 循环实际上做了什么,我将不胜感激:
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
.据我了解,它应该创建一个矩阵向量
A
(其中 m 个)以及一个 m 维向量b
。 I am totally confused though on the indexing of A
and the indexing of b
.我对
A
的索引和b
的索引完全感到困惑。
I would like an explanation of the :, (i-1)*n+1:i*n
part of this code .我想解释一下这段代码的
:, (i-1)*n+1:i*n
部分。 The reason I ask here is because I also dont know what to Google or what to search for in Julia documentation.我在这里问的原因是因为我也不知道谷歌或在 Julia 文档中搜索什么。
(i-1)*n+1:i*n
creates a range from (i-1)*n + 1
to i*n
. (i-1)*n+1:i*n
创建一个从(i-1)*n + 1
到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.例如,如果
i
=2 且n
=10,则此范围变为11:20
,因此A[:, (i-1)*n+1:i*n]
将抓取A
的所有行(这就是:
所做的) 和第 11-20 列。
There are two operations there that are not clear to you:那里有两个你不清楚的操作:
:
operator. :
运营商。 Consider a Matrix
a = zeros(3,3)
.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]
.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)end
的所有内容时,都可以省略这两个值,因此您可以编写a[:,2]
(这总是看来是我记住这一点的最简单方法).
(dot) operator. a[:, 2] = 5.0
will throw an error because there is vector on the right and a scalar on the left.a[:, 2] = 5.0
将值分配给第二列将引发错误,因为右侧有向量,左侧有标量。 If you want to vectorize you need to tell that to Julia..=
means "perform element-wise assignment"..=
表示“执行元素赋值”。 Note that any Julia function or operator, even your own functions can be decorated by such dot .
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.