3

In Julia I created a Matrix A and want to set its value at (1, 1) to the value of 5. How do I do that? I tried this:

A = zeros(5, 5)
A[1][1] = 5

It throws the error

MethodError: no method matching setindex!(::Float64, ::Int64, ::Int64)

Stacktrace:
 [1] top-level scope
   @ In[38]:4
 [2] eval
   @ .\boot.jl:373 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1196

1 Answers1

0

DNF's comment already gives you the answer, but I'll elaborate a little.

The basic issue with what you're doing is that A[1] is a valid indexing operation returning the first element of A, and therefore A[1][1] is trying to index into that first element, which is just a number. To see:

julia> A[1]
0.0

julia> A[1][1]
0.0

Essentially what you are doing is equivalent to this:

julia> x = 1
1

julia> x[1] = 2
ERROR: MethodError: no method matching setindex!(::Int64, ::Int64, ::Int64)
Stacktrace:
 [1] top-level scope
   @ REPL[12]:1

numbers in Julia are immutable, i.e. you cannot "replace" a number with another number in place. Arrays on the other hand are mutable:

julia> y = [1]
1-element Vector{Int64}:
 1

julia> y[1] = 2
2

So you could also have done:

julia> A[1] = 5
5

julia> A
5×5 Matrix{Float64}:
 5.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0

Why does A[1] work? A single index will give you the element you arrive at when you count down row-wise, continuing at the next column when you get to the bottom:

julia> z = rand(2, 2)
2×2 Matrix{Float64}:
 0.727719  0.983778
 0.792305  0.0408728

julia> z[3]
0.9837776491559934
Nils Gudat
  • 13,222
  • 3
  • 39
  • 60