Stream: helpdesk (published)

Topic: kronecker products with a vector of only one non-zero ele...


view this post on Zulip Dominic Guri (May 07 2021 at 19:27):

I have something like kron(h, A), A is some matrix. The silly problem is that h is all zeros except for one index. So I write something like this

l  = 100;   # some large number
h = zeros(l);
h[k] = 1;

Is there a better one-liner for this?
So far, I came up with h(l,k)=1.0*(k .== (1:l))

view this post on Zulip Mason Protter (May 07 2021 at 19:39):

The multiplication by 1.0 shouldn't be necessary

view this post on Zulip Mason Protter (May 07 2021 at 19:42):

julia> A = reshape(1.0:4.0, 2, 2)
2×2 reshape(::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}}, 2, 2) with eltype Float64:
 1.0  3.0
 2.0  4.0

julia> h = (1:4) .== 3
4-element BitVector:
 0
 0
 1
 0

julia> kron(A, h)
8×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0
 1.0  3.0
 0.0  0.0
 0.0  0.0
 0.0  0.0
 2.0  4.0
 0.0  0.0

view this post on Zulip Mason Protter (May 07 2021 at 19:45):

If you want h as a matrix, one thing you can do it a pattern like this:

julia> Iterators.product(1:3, 1:3) .== ((3, 2),)
3×3 BitMatrix:
 0  0  0
 0  0  0
 0  1  0

view this post on Zulip Mason Protter (May 07 2021 at 19:45):

Do you mind if I move this topic to #helpdesk or #helpdesk (published) ?

view this post on Zulip Dominic Guri (May 07 2021 at 20:14):

Sure, move it whichever channel is the best fit. I just thought it was an annoyance more than problem :)

view this post on Zulip Mason Protter (May 07 2021 at 20:36):

I think it's a good question :smile:

view this post on Zulip Notification Bot (May 07 2021 at 20:37):

This topic was moved here from #random > kronecker products with a vector of only one non-zero ele... by Mason Protter

view this post on Zulip Michael Abbott (May 09 2021 at 06:00):

If you do weird kronecker products, then I have a package you may like:

julia> using TensorCast

julia> @cast B[(i,k),j] := (k==2) * A[i,j]   (k in 1:3)
6×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0
 1.0  3.0
 2.0  4.0
 0.0  0.0
 0.0  0.0

julia> @cast B[(i,k),j] := k==2 ? A[i,j] : 0  (k in 1:3)   # 0.0 would be better
6×2 Matrix{Real}:
 0    0
 0    0
 1.0  3.0
 2.0  4.0
 0    0
 0    0

Last updated: Nov 22 2024 at 04:41 UTC