Can I do the opposite of what a view does?

Suppose I have a 1-d array named A. I would like to create a “view” of A called B such that B[i,j] = A[i] for any j. Is there a simple way of doing that? This is the opposite of how I understand a view refers to a slice of a larger array.

You could define a struct, which takes the array or a reference of it and define a custom getindex function which ignores j and delegates to the array.

2 Likes

Hi @alisdairmckay, welcome to the community!

Could you explain further what are you doing and why is a view not doing what you want?

If you want to do some summations over indices Tullio.jl might be what you want. GitHub - mcabbott/Tullio.jl: ⅀

This can be supported by a view, but you do have to know how big you want B to end up:

julia> A = rand(10)
10-element Vector{Float64}:
 0.42586812374883776
 0.33987994634118457
 0.14657493603322203
 0.5526207422678311
 0.020943403607115663
 0.5493698194675869
 0.13079022482415348
 0.543093894474816
 0.21883580282653958
 0.24330808910869095

julia> B = @view A[:, fill(1, 10)]
10×10 view(::Matrix{Float64}, :, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) with eltype Float64:
 0.425868   0.425868   0.425868   0.425868   0.425868   0.425868   0.425868   0.425868   0.425868   0.425868
 0.33988    0.33988    0.33988    0.33988    0.33988    0.33988    0.33988    0.33988    0.33988    0.33988
 0.146575   0.146575   0.146575   0.146575   0.146575   0.146575   0.146575   0.146575   0.146575   0.146575
 0.552621   0.552621   0.552621   0.552621   0.552621   0.552621   0.552621   0.552621   0.552621   0.552621
 0.0209434  0.0209434  0.0209434  0.0209434  0.0209434  0.0209434  0.0209434  0.0209434  0.0209434  0.0209434
 0.54937    0.54937    0.54937    0.54937    0.54937    0.54937    0.54937    0.54937    0.54937    0.54937
 0.13079    0.13079    0.13079    0.13079    0.13079    0.13079    0.13079    0.13079    0.13079    0.13079
 0.543094   0.543094   0.543094   0.543094   0.543094   0.543094   0.543094   0.543094   0.543094   0.543094
 0.218836   0.218836   0.218836   0.218836   0.218836   0.218836   0.218836   0.218836   0.218836   0.218836
 0.243308   0.243308   0.243308   0.243308   0.243308   0.243308   0.243308   0.243308   0.243308   0.243308

A FillArray or a 0-step range from Julia 1.7 as the column index would make that more efficient.

5 Likes

This also seems like a weird thing to look for (if you know you are actually indexing a vector, why not just drop the additional dimensions?). I’d say if you find yourself needing this, perhaps you are doing something in a less-than-straightforward way. If you provide more detail on your problem, perhaps we can get you an even better solution.

1 Like

I could image a special type of “sparse” matrix where every column is the same with n X infinite size.

Thanks for comment. You are probably right that I could do something simpler. This is an instance of needing a 2-d peg to fit into a 2-d hole.