Boundserror: attempt to access 120 times 1 matrix{Float} at index [1,3]

Pout[:, 3:5] = X[:, 3:5]
for i in 1:3
PF_coe = Param_5[2 + i]
for j in 1:120
Qout[j, 2 + i] = Pout[j, 2 + i] * PF_coe
end
end
Not understand why it keeps resulting in the boundserror, I did not find where it is wrong. Could anyone help me to solve this problem?

Julia is column major, the first index is the column index:

julia> a = [1; 2; 3;;]
3×1 Matrix{Int64}:
 1
 2
 3

julia> a[1,3]
ERROR: BoundsError: attempt to access 3×1 Matrix{Int64} at index [1, 3]
Stacktrace:
 [1] getindex(::Matrix{Int64}, ::Int64, ::Int64)
   @ Base ./essentials.jl:14
 [2] top-level scope
   @ REPL[3]:1

julia> a[3,1]
3

I agree that the problem seems to be that

Qout[j, 2 + i] = Pout[j, 2 + i] * PF_coe 

should be

Qout[2 + i, j] = Pout[2 + i, j] * PF_coe

But this:

is unrelated. The first index is the row index in both column major and row major languages.

I think it’s considerably more likely that Qout doesn’t have enough columns on construction and that this code is ported from Matlab where indexing out of bounds on the left hand side magically adds columns.

octave:1> q = zeros(120, 1);
octave:2> q(1, 3) = 1;
octave:3> size(q)
ans =

   120     3
julia> q = zeros(120, 1);

julia> q[1, 3] = 1
ERROR: BoundsError: attempt to access 120×1 Matrix{Float64} at index [1, 3]
1 Like

It’s a difference in perspective - I take the first index to mean “which column should I look at?”, while you take it to mean “which element of the row should I look at?”. I.e., what I called “column index” is the “index of the column in the row”. From my POV, the second index gives me the row of a column, and the first index gives me the column in a table.

That’s also a good point - perhaps @Xiaoting_Wang can clarify?

No, I take the first index to mean which row to look at. And so do you, I suspect, you’re just mixing it up at the moment.

But my main point was that row major and column major languages have precisely the same meaning for the order of indices. The only difference is the memory layout, which is not visible to the user.

3 Likes

You’re right, in that message I was mixing things up - I was thinking of “which element in the column” (i.e., the index into the column), not “which column”!