Assign values to Julia Matrix based on Condition

时间:2019-04-16 23:08:38

标签: julia

I have a matrix of zeros A which has dimension (m x n). I have another matrix of some integer values b. b has length n. I want to have A be set to the identity wherever b has values greater than 5. So basically, for every row of A where b has value greater than 5, set it to the identity.

I tried to do this, but it's not working. Does anyone have an idea of how to do this in Julia?

using LinearAlgebra
usable_values = filter((x) -> x > 5, b)
# A[:, usable_values] = I
A[:, b .> 5] = I

2 个答案:

答案 0 :(得分:1)

If what you need is for every row of A where b has value greater than 5, set it to the identity this might be helpful to you, while you wait that for some of the gurus here can write the same in one line of code :)

n = 2
m = 5
A = zeros(m, n)
b = rand(1:10, m)

println(b)

for (cnt, value) in enumerate(b)
    if value > 5
        A[cnt, :] = ones(1, n)
    end
end
A

The result I get is:

b = [4, 2, 6, 8, 1]

5×2 Array{Float64,2}:
0.0  0.0
0.0  0.0
1.0  1.0
1.0  1.0
0.0  0.0

I am fairly new to the language, this is the best I can do to help, for now.

答案 1 :(得分:1)

我不确定我是否理解“设置为身份”的含义:身份矩阵必须为正方形,因此矩阵的行或列不能等于身份矩阵。我将假设您希望条目具有值1。在这种情况下,

A[:, findall(b .> 5)] .= 1

是一个简单的单行代码。让我们在这里讨论元素:

  • 如上所述,filter将选择大于5的b元素。但是您需要这些元素的索引,其中findall是合适的函数。
  • 请注意广播分配.=的使用。这意味着将RHS分配给左侧的每个元素。这样,您无需在RHS上创建矩阵。

循环方法也很好,但是出于性能的考虑,我将其放在函数中。参见performance tips