pooooky
pooooky

Reputation: 520

How to create array comprehension in Julia with two dimentions

I'm new to Julia, and I wanted to learn how to do an array comprehension. I have this lines of code:

for i in 1:m
    for j in 1:n
        arr[i, j] = i + j
    end
end

I want to do the same thing with an array comprehension. I wrote this the below code, but I know this is not an array comprehension. Please help me create an array comprehension.

for i in 1:m, j in 1:n
    arr[i, j] = i + j
end

Thank you so much!

Upvotes: 7

Views: 204

Answers (2)

longemen3000
longemen3000

Reputation: 1313

your code has a little typo:

for i in 1:m, j in 1:n #Julia loops can iterate over multiple indices at once
    arr[i, j] = i + j
end

but that is not a comprehension, is just a regular for loop.

Upvotes: 2

bichanna
bichanna

Reputation: 1044

The more Julian way of filling the array would be this (of course, I'm using an array comprehension):

arr = [i + j for i in 1:m, j in 1:n]

Upvotes: 8

Related Questions