If you're looking for a one-liner, this works:

for i in 1:10 tmp[1:i,i] = rand(i) end

It looks gross at first, but eventually the brain parses it just fine. 
`end` is just a very verbose closing parenthesis.

On Tuesday, February 2, 2016 at 10:17:56 AM UTC-5, Stefan Karpinski wrote:
>
> As you suspect, assignment inside of comprehensions is and antipattern. It 
> *will* allocate the result array of arrays and then throw it away. This 
> could potentially be optimized away, but why not just use a for loop?
>
> On Tue, Feb 2, 2016 at 4:00 AM, Ján Dolinský <[email protected] 
> <javascript:>> wrote:
>
>> Hi,
>>
>> Is an assigment inside a comprehension a "good practice" e.g. I want to 
>> fill in columns of a temporary matrix as follows:
>>
>> tmp = zeros(10,10)
>>
>> # this is flawless
>> for i in 1:10
>>  tmp[1:i,i] = rand(i)
>> end
>>
>> # this is a neat one line expression but I wonder whether it does not 
>> silently allocate result outside of the comprehension
>> [ tmp[1:i,i] = rand(i) for i in 1:10 ]
>> # e.g. here "x" becomes a vector of vectors ...
>> x = [ tmp[1:i,i] = rand(i) for i in 1:10 ]
>>
>> Thanks for an advice,
>> Jan
>>  
>>
>
>

Reply via email to