Hi, I’m a long term Matlab user just starting to wade into the world of Julia, so forgive me if my question is naive.
I’m am currently writing some code to perform a number of matrix manipulation tasks. I came across what to me seems like a limitation of the * operator on Arrays. Since I am new to Julia, I think the limitation is probably my understanding, not the language.
Say I have the following function
function double(A::Array{<:Real}, B::Array{<:Real})
C = A*B
2*C
end
which I evaluate as follows
julia> A = [1 2;3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> B = [5;6]
2-element Array{Int64,1}:
5
6
julia> double(A,B)
2-element Array{Int64,1}:
34
78
This all works as expected. Now what if A and B are defined as shown below
julia> A = [1;2]
2-element Array{Int64,1}:
1
2
julia> B = [3]
1-element Array{Int64,1}:
3
julia> double(A,B)
ERROR: MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64,1})
So even though this multiplication is mathematically valid it doesn’t evaluate successfully. I have solved this by extending the the * operator using the following function
function Base.:*(A::Array{<:Number,1}, B::Array{<:Number,1})
if length(A) == 1
A[1]*B
elseif length(B) == 1
A*B[1]
else
error("Array dimensions not suitable for multiplication.")
end
end
This works fine, however, it feels to me like this is not good practice. I was hoping someone could provide some advice on a more “Julian” way of dong this, or if this is indeed a suitable approach.
Thanks in advance, Will.