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

How to add arrays with different offsets? #45

Closed
suiato opened this issue Apr 24, 2018 · 1 comment
Closed

How to add arrays with different offsets? #45

suiato opened this issue Apr 24, 2018 · 1 comment

Comments

@suiato
Copy link

suiato commented Apr 24, 2018

I wanted to add two arrays with different offsets assuming zero-padding, and tried to use paddedviews(). But, didn't work :-(
So, I tried to create a function to do that... Below is my first attempt in a one-dimentional case.
Before extending it to multi-dimensional arrays, it looks already pretty complicated :-(

Are there better ways to do that?

using OffsetArrays
a = [1,2,3]; b = [4,5,6];
a_o = OffsetArray(a, -2); b_o = OffsetArray(b, 1);
function add_offsets(a_o, b_o)
    a_r = indices(a_o); b_r = indices(b_o);
    a_min = minimum.(a_r)[1]; a_max = maximum.(a_r)[1];
    b_min = minimum.(b_r)[1]; b_max = maximum.(b_r)[1];
    ab_min = min(a_min, b_min); ab_max = max(a_max, b_max);
    a_p = zeros(eltype(a_o), ab_max - ab_min + 1)
    a_p = OffsetArray(a_p, ab_min:ab_max)
    a_p[a_min:a_max] = a_o[a_min:a_max]
    a_p[b_min:b_max] += b_o[b_min:b_max]
    a_p
end
add_offsets(a_o, b_o)
@timholy
Copy link
Member

timholy commented Nov 13, 2018

I don't think we want to support this operation. After all:

 julia> rand(2) + rand(2)
2-element Array{Float64,1}:
 0.903664522947776 
 1.6401079495522737

julia> rand(2) + rand(3)
ERROR: DimensionMismatch("dimensions must match")
Stacktrace:
 [1] promote_shape at ./indices.jl:154 [inlined]
 [2] promote_shape(::Array{Float64,1}, ::Array{Float64,1}) at ./indices.jl:145
 [3] +(::Array{Float64,1}, ::Array{Float64,1}) at ./arraymath.jl:45
 [4] top-level scope at none:0

and that's the way it should be. Likewise, when you're thinking about offset arrays, a location is specified by its indices and so if two arrays don't have all their indices in common, you're essentially asking to make up missing data.

Padding both arrays to have the same indices is definitely the way to go here. Perhaps file an issue over at PaddedViews if something isn't working.

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

2 participants