hhillman231
hhillman231

Reputation: 155

for loop in Julia - iterating over an entire index

I'm having trouble getting Julia to go through all the numbers in a matrix:

A = [1 -2 3; -4 -5 -6; 7 -8 9]

I want to turn all of the negative numbers into a positive 3

I tried:

for i=A[1:end]
  if i<0
    A[i] = 3
    i += 1
  end
  return (A)
end

I've tried moving the i+=1 to various positions. But still it's not changing anything.

Upvotes: 3

Views: 6556

Answers (3)

David Scholz
David Scholz

Reputation: 9856

There is another alternative. We can use foreach.

A = [1 -2 3; -4 -5 -6; 7 -8 9]
foreach(j->A[j]=A[j] < 0 ? 3 : A[j], 1:1:length(A))

which yields to

3×3 Matrix{Int64}:
 1  3  3
 3  3  3
 7  3  9

as desired.

Upvotes: 0

tpdsantos
tpdsantos

Reputation: 443

As an alternative to eachindex, you can iterate over a range, in this case the range of indices, like in MatLab.

for i = 1:length(A)
    if A[i] < 0
        A[i] = 3
    end
end

Upvotes: 0

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

Try enumerate:

julia> A = [1 -2 3; -4 -5 -6; 7 -8 9]
3×3 Array{Int64,2}:
  1  -2   3
 -4  -5  -6
  7  -8   9

julia> for (i,v) in enumerate(A)
       if v < 0
       A[i] = 3
       end
       end

julia> A
3×3 Array{Int64,2}:
 1  3  3
 3  3  3
 7  3  9

or eachindex:

julia> A = [1 -2 3; -4 -5 -6; 7 -8 9]
3×3 Array{Int64,2}:
  1  -2   3
 -4  -5  -6
  7  -8   9

julia> for i in eachindex(A)
       if A[i] < 0
       A[i] = 3
       end
       end

julia> A
3×3 Array{Int64,2}:
 1  3  3
 3  3  3
 7  3  9

You can find details about those functions in interactive help in Julia REPL.

Upvotes: 7

Related Questions