bitWise
bitWise

Reputation: 709

Why doesn't julia broadcasting work when deals with more than one array?

I have defined two structs and a function like this

struct A
    x::Float64
end

struct B
    y::Float64
end

f(a::A, b::B) = a.x*sin(b.y)
f.([A(0.1), A(0.2)], [B(1.), B(2.), B(3.)])

But f returns this error:

DimensionMismatch("arrays could not be broadcast to a common size")

How can I solve this error? I expect an array with 6 elements as the function output.

Upvotes: 3

Views: 678

Answers (2)

AshtonBradley
AshtonBradley

Reputation: 136

The arrays have to have compatible dimensions - either identical in size and shape (local operations), or they span a larger vector space where each has singleton dimensions where the others have non-singleton dimensions, e.g. as an operation on the dimensions, the .* operator will cause the mapping

(1 x 1 x n) .* (p x q x 1)  => p x q x n

Upvotes: 1

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69829

The problem is that your first argument is a 2-element Vector, and a second argument is 3-element Vector.

If you e.g. make the first argument a 1x2 Matrix, then all works fine:

julia> f.([A(0.1) A(0.2)], [B(1.), B(2.), B(3.)])
3×2 Array{Float64,2}:
 0.0841471  0.168294
 0.0909297  0.181859
 0.014112   0.028224

(note that the missing or 1-length dimensions get automatically broadcasted)

Note that you could also broadcast calls to A and B constructors:

f.(A.([0.1 0.2]), B.(1.:3.))

Upvotes: 5

Related Questions