My problem is as follows:
I have a 3D array (6:2:7*) with 6 rows (fixed), 2 columns (fixed), 7 pages (* may vary up to 100 )
I would like to concatenate this 3D array into a 2D array (6*7*:2) (* again, that 7 may vary up to 100 )
I need to maintain the the column-wise behavior of this 3D array into the 2D array (xy coordinates)
My question is - do I need a for loop to achieve this? If so, how?
I can type this operation out manually and achieve my desired result with the code below: 3D array = xy3d 2D array = xy
xy = cat(1,xy3d(:,:,1),...
xy3d(:,:,2),...
xy3d(:,:,3),...
xy3d(:,:,4),...
xy3d(:,:,5),...
xy3d(:,:,6),...
xy3d(:,:,7)); %Produces xy(42:2) when...xy3d(6:2:7)
CodePudding user response:
You can do it with a loop, but you can also use permute
to get the data in the right order, and then reshape
to get the array in the desired shape.
You need to be aware of the storage order. MATLAB stores data column-wise. That is, the element (1,1,1) comes first, then (2,1,1), then (3,1,1), … then (1,2,1), (2,2,1), … then (1,1,2), etc etc.
reshape
doesn’t change the storage, so applying it directly on your array will not produce the right result. The array would contain in the first column the first half of the data (from both columns, to half-way along the 3rd dimension), the remainder in the 2nd column. That is, individual x-y pairs would be split up.
We first need permute
to move the 2nd dimension to the end. This will copy the data. Now the first half of the data in memory will be all the x components, the second half the y components. The reshape
after will not copy data, it will just make one column out of the first half of the data and a second column out of the second half.
xy = permute(xy3d, [1,3,2]);
xy = reshape(xy, [], 2);
The []
in the reshape call indicates put as many elements in the 1st dimension as needed, for the 2nd dimension we specify 2.