# Dividing matrix into sections

#1

How to divide a matrix like m x n or an Array like m x n x 1 into topographic sections? Imagine dividing a square into smaller squares.
And operating individually on those sections.
Edit: The actual problem is that I want to know the indices of each element of each section the way they are stored in the parent matrix

#2

Maybe I am missing something, but possibly with indexing and views? Eg

julia> A = zeros(3, 3);

julia> Av = @view A[1:2, 1:2];

julia> Av .= ones(2, 2);

julia> A
3×3 Array{Float64,2}:
1.0  1.0  0.0
1.0  1.0  0.0
0.0  0.0  0.0


#3

But how will we do this for the entire matrix? Say you wish to divide it into 6 squares.

#4

You specify the division and map it to views. (If you have a concrete example of what you want, I could help with code).

#5
a = rand(1:100, 25, 25, 1)
i, j, one = size(a)
for m in 1:i, for n in 1:j
display(a[max(1, m-4):min(25, m+4), max(1, n-4):min(25, n+4)])
end


#6
a = rand(1:100, 25, 25, 1)
i, j, _ = size(a)               # replace one, don't overwrite that function
V = [@view(a[max(1, m-4):min(25, m+4), max(1, n-4):min(25, n+4), :]) # added a :
for m in 1:i for n in 1:j] # note nesting order, is this what you want?


This gives you a vector of views, you can modify the comprehension to make a matrix if that’s what you need.

#7

That’s not what I want. It’s just a workaround to store views which I was aware of. I was looking for a function to divide a matrix into mostly equal squares so that I can run a function over those individual sections.
But now I realize that the actual problem is that I still want to somehow know the indices of each element of each section the way they are stored in the parent matrix

#8

Well, there is Base.parent and Base.parentindexes. I don’t know the details of your calculation, but this may be a very roundabout way of going about it.

#9

Take a look at https://github.com/JuliaArrays/TiledIteration.jl

#10

Thanks a lot.

#11

Or alternatively https://github.com/JuliaImages/ImageFiltering.jl which are general array operations, not just for images.

#12

For square matrices of size n\times n, for example, this can be easy:


n = 1024
bSize = 16
A = rand(n,n)
for j = 1:bSize:n, i = 1:bSize:n
tempArray = @view A[i:i+bSize-1,j:j+bSize-1]
# do calculations on tempArray
end


For general rectangular matrices m\times n, you need a row_bSize and another col_bSize, such that row_bSize divides m and col_bSize divides n but the idea is the same. If the blocks need to be squares, then row_bSize = col_bSize and m or n are divisible my either of them.

#13