1
votes

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
A[:, b .> 5] .= I? Note the dot before equal sign. - 张实唯
and for the first approach, use findall instead of filter, which returns the indexes of those meet the condition. - 张实唯
@张实唯 It gives me an error: MethodError: no method matching length(::UniformScaling{Bool}) - hockeybro
sorry for being too lazy to provide a full working example, but luckily there is tholy :) Just see his great long answer. - 张实唯

2 Answers

1
votes

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
votes

I'm not certain I understand what you mean by "set to the identity": the identity matrix must be square, and hence a row or column of a matrix can't be equal to the identity matrix. I'll operate under the assumption that you want the entries to have value 1. In that case,

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

is a simple one-liner. Let's discuss the elements here:

  • As proposed above, filter will select out the elements of b bigger than 5. But you want the indices of those elements, for which findall is the appropriate function.
  • Note the use of broadcasted assignment, .=. This means to assign the RHS to each element of the left side. That way you don't need to create a matrix on the RHS.

The loop approach is fine too, but for reasons of performance I'd put that in a function. See the performance tips.