0

I am writing some code, whereby I store a greyscale image, which is split into 'blocks' in a 4D array. I will be looping through all the 'blocks' in the 4D array and will perform calculations based on the contents of the blocks compared to one another. I want to only compare the 'blocks' that are near each other, and to do this I can just calculate the distance between the 'blocks' and don't loop through the ones that are too far away. To do this I need the index of each 'block' in the 4D matrix, ultimately creating my question.

My code goes like this:

for i=4dmatrix1
    for j=4dmatrix2
        % Do calculations here involving the index of i
        % and j in their respective matrices.
    end
end

I have i and j, but I want to find their index in 4dmatrix1 and 4d matrix2 respectively. 4dmatrix1 and 4dmatrix2 are greyscaled images that have been split into "blocks" of 20x20 pixels. Each matrix in 4dmatrix1 and 4dmatrix2 is a "block" in image 1 and image 2. The reason I have used this method for storing the data as it still represents the shape of the image, just split into 20x20 blocks. In my head this is understandable, but maybe for programming, this is inefficient and should be changed. If so, what would you recommend looking into?

Thank you!

S_Zizzle
  • 95
  • 1
  • 12
  • For indexing questions I can recommend [this Q/A](https://stackoverflow.com/q/32379805/5211833) which lists all the different kinds of indexing. – Adriaan Nov 13 '18 at 21:38
  • This indexing Q/A doesn't specify anything about multidimensional arrays, only 2D arrays. – S_Zizzle Nov 13 '18 at 21:55

1 Answers1

0

You can loop over the indices of a matrix in any dimension, and then map that to the subscripts using ind2sub. Basically, the syntax would be

[id1,id2,id3,id4] = ind2sub(size(my4Dmatrix, i));

And something similar for j.
Not really your question, but something doesn't seem quite right with how you're looping. Also, you should include a minimum working example, including generating a couple of matrices and using correct syntax (you cannot start a variable name in MATLAB with a number).

Steve Heim
  • 799
  • 12
  • 25