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))
The multiplication by 1.0
shouldn't be necessary
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
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
Do you mind if I move this topic to #helpdesk or #helpdesk (published) ?
Sure, move it whichever channel is the best fit. I just thought it was an annoyance more than problem :)
I think it's a good question :smile:
This topic was moved here from #random > kronecker products with a vector of only one non-zero ele... by Mason Protter
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 06 2024 at 04:40 UTC