Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 938
hhillman231 Avatar asked Jan 19 '26 03:01

hhillman231


1 Answers

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.

like image 139
Bogumił Kamiński Avatar answered Jan 20 '26 17:01

Bogumił Kamiński