Hello dear Matlab experts,
I have an array of images, let's say a 2 by 3 grid of images (6 images). Each image has a resolution of 4 x 4 (for simplicity). Lets say the images are grayscale.
I loaded the images into a 4D matrix with dimensions 2 x 3 x 4 x 4. Now I want to create a column vector with entries
1: first pixel of first row in image 1,1
2: second pixel of first row in image 1,1
3: ...
16: last pixel of last row in image 1, 1
17: first pixel of first row in image 2, 1
...
and so on goes the pattern. I could successfully create this with a bunch of for loops:
for imageX = 1 : resolution(2)
for imageY = 1 : resolution(1)
for pixelX = 1 : resolution(4)
for pixelY = 1 : resolution(3)
% linear index for 4D indices
row = ((imageY - 1) * resolution(2) + imageX - 1) * resolution(3) * resolution(4) + ...
(pixelY - 1) * resolution(4) + pixelX;
lightFieldVector(row) = lightField(imageY, imageX, pixelY, pixelX);
end
end
end
end
I am wondering if this ugly pile of loops can be replaced by a few reshape
and permute
operations. I think so, but I have trouble finding the right order. I used these methods a few times, but only with 2D matrices. From the documentation I can conclude that reshaping will go 'column first', so this would be the opposite I need.
I appreciate your help, Adrian
This should be the right order -
lightFieldVector = reshape(permute(lightField,[4 3 2 1]),[],1)
The whole play here is about knowing linear indexing
and permute
in MATLAB.
The reverse process -
R = resolution
lightField = permute(reshape(lightFieldVector,R(4),R(3),R(2),R(1)),[4 3 2 1])