There are also a couple of more concise options in Base.

For multiplication by a constant, you can also use scale!(b, 2), which will 
basically do the same thing as Tim's loop for SharedArrays, but may be 
faster for arrays of BLAS types since it calls BLAS scal!.

For elementwise operations on multiple arrays, you can use broadcast!(fn, 
dest, A, B, ...), where fn is the operator, dest is the array where the 
result is to be stored (which may be A or B, and may be a SharedArray), and 
A and B are input arrays. (This works for any number of input arrays.)

I'm not sure if there's a solution for adding a scalar that doesn't involve 
a loop.

On Thursday, February 20, 2014 12:09:32 PM UTC-5, Jonathan Malmaud wrote:
>
> The devectorize package https://github.com/lindahua/Devectorize.jl can 
> deal with this:
> f(x) = @devec x[:]=2.*x
>
> 'f' won't allocate any new memory.
>
> On Wednesday, February 19, 2014 12:11:02 PM UTC-8, Tim Holy wrote:
>>
>> Unfortunately, I'm pretty sure you can't do what you're hoping for. 
>> Consider: 
>>
>> julia> A = rand(2,2) 
>> 2x2 Array{Float64,2}: 
>>  0.63259   0.109017 
>>  0.667425  0.112597 
>>
>> julia> pointer(A) 
>> Ptr{Float64} @0x000000000446f6a0 
>>
>> julia> A *= 2 
>> 2x2 Array{Float64,2}: 
>>  1.26518  0.218033 
>>  1.33485  0.225195 
>>
>> julia> pointer(A) 
>> Ptr{Float64} @0x0000000005696650 
>>
>> I think A *= 2 gets translated by the parser into A = A*2. There are some 
>> old 
>> posts that can do a better job than I explaining why this is important. 
>>
>> So I think your only bet is to do something like this: 
>>
>> for i = 1:length(A) 
>>     A[i] *= 2 
>> end 
>>
>> which does work in-place. 
>>
>> --Tim 
>>
>> On Wednesday, February 19, 2014 11:26:48 AM Madeleine Udell wrote: 
>> > Currently in-place arithmetic operations turn shared arrays into normal 
>> > ones: eg 
>> > 
>> > b = Base.shmem_randn(10) 
>> > b *= 2 
>> > 
>> > results in b becoming a (not-shared) array. I'd like to overload these 
>> > in-place arithmetic operations so that instead of writing 
>> > 
>> > typeof(b)==SharedArray? b.s *= 2 : b *= 2 
>> > 
>> > I can just write 
>> > 
>> > b *= 2 
>> > 
>> > and know that the shared status of my array will be preserved. How 
>> might 
>> > one overload these operations? 
>> > 
>> > (Note: I don't want c = b + b to automatically create a shared array c, 
>> > since that allocates new shared memory.) 
>>
>

Reply via email to