How to create array comprehension in Julia with two dimentions

Viewed 102

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!

2 Answers

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]

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.

Related