where r is an n dimensional array and A is an nxn matrix which may or may not be sparse. Evaluating this on a single r and A works fine. However, for a fixed A, if I try to evaluate on many r’s via vectorization, I get the error:
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Here is a complete sample code that produces this error:
function energy(r,A)
return 0.5 * dot(r, A*r)
end
A = [1. 2.; 2. 1.]
r = [1.,0.5]
energy(r,A) # this works fine
x = linspace(-1,1, 10)|>collect
y = linspace(-1,1, 10)|>collect
rvals = [[x[j],y[i]] for i=1:length(y), j = 1:length(x)];
energy.(rvals,A) # this generates the error
Julia is interpreting your command as an attempt to broadcast over the elements of rvals and the elements of A simultaneously, but you actually want it to use the entirety of A for every call. In essence you want rvals to be treated like an array in the broadcast, but for A to be treated like a scalar so that it is passed intact to each call to energy. You can make any item behave like a scalar in broadcasting by simply wrapping it in a one-element tuple: