Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling hvcat #1262

Open
3f6a opened this issue Jun 23, 2024 · 3 comments
Open

Handling hvcat #1262

3f6a opened this issue Jun 23, 2024 · 3 comments

Comments

@3f6a
Copy link

3f6a commented Jun 23, 2024

julia> t = @SMatrix randn(2,2)
2×2 SMatrix{2, 2, Float64, 4} with indices SOneTo(2)×SOneTo(2):
 -0.427379  -0.583282
 -0.099235  -0.644796
julia> [t t]
2×4 SMatrix{2, 4, Float64, 8} with indices SOneTo(2)×SOneTo(4):
 -0.427379  -0.583282  -0.427379  -0.583282
 -0.099235  -0.644796  -0.099235  -0.644796

In this example, the concatenated [t t] correctly returns a SMatrix. However,

julia> [t t; t t]
4×4 Matrix{Float64}:
 -0.427379  -0.583282  -0.427379  -0.583282
 -0.099235  -0.644796  -0.099235  -0.644796
 -0.427379  -0.583282  -0.427379  -0.583282
 -0.099235  -0.644796  -0.099235  -0.644796

returns a raw Matrix instead. It seems hvcat is not correctly overloaded.

@david-macmahon
Copy link

Here's some more detail:

julia> @code_lowered [t t]
CodeInfo(
1 ─      nothing
│   %2 = StaticArrays.Size(a)
│   %3 = StaticArrays.Size(b)
│   %4 = StaticArrays._hcat(%2, %3, a, b)
└──      return %4
)

julia> @code_lowered [t;t]
CodeInfo(
1 ─      nothing
│   %2 = StaticArrays.Size(a)
│   %3 = StaticArrays.Size(b)
│   %4 = StaticArrays._vcat(%2, %3, a, b)
└──      return %4
)

julia> @code_lowered [t t; t t]
CodeInfo(
1 ─ %1 = Base.typed_hvcat
│   %2 = Core.tuple($(Expr(:static_parameter, 1)), rows)
│   %3 = Core._apply_iterate(Base.iterate, %1, %2, xs)
└──      return %3
)

@david-macmahon
Copy link

This can be worked around by forcing the hcat and vcat to be separate (my t had different values):

julia> [[t t];[t t]]
4×4 SMatrix{4, 4, Float64, 16} with indices SOneTo(4)×SOneTo(4):
  0.723556  -0.644347   0.723556  -0.644347
 -0.031864  -1.14712   -0.031864  -1.14712
  0.723556  -0.644347   0.723556  -0.644347
 -0.031864  -1.14712   -0.031864  -1.14712

@mateuszbaran
Copy link
Collaborator

Note also:

julia> f(t) = [t t; t t]
f (generic function with 1 method)

julia> @code_lowered f(t)
CodeInfo(
1%1 = Core.tuple(2, 2)
│   %2 = Base.hvcat(%1, t, t, t, t)
└──      return %2
)

We need to statically know %1 to have the type of the returned static array be type-stable, which may not be particularly reliable. We generally prefer type-stable Array over type-unstable StaticArray as a result type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants