tehm0n
tehm0n

Reputation: 79

Reshape 2-D matrix with a specific format into a 3-D matrix (MATLAB)

I have a Cartesian 2-D matrix, A, that contains bins of dose values in three (X,Y,Z) dimensions;

Therefore, the total number of elements in A is nx*ny*nz=29622272. When reading a .dat-file, the data in matrix A are stored in the following format

A(1,1,1) A(2,1,1) A(3,1,1) A(4,1,1) A(5,1,1) A(6,1,1) A(7,1,1) A(8,1,1) A(9,1,1) A(10,1,1)

A(11,1,1) A(12,1,1) A(13,1,1) A(14,1,1) A(15,1,1) A(16,1,1) A(17,1,1) A(18,1,1) A(19,1,1) A(20,1,1)

A(503,1,1) A(504,1,1) A(505,1,1) A(506,1,1) A(507,1,1) A(508,1,1) A(509,1,1) A(510,1,1) A(511,1,1) A(512,1,1)

A(1,2,1) A(2,2,1) A(3,2,1) A(4,2,1) A(5,2,1) A(6,2,1) A(7,2,1) A(8,2,1) A(9,2,1) A(10,2,1)

A(11,2,1) A(12,2,1) A(13,2,1) A(14,2,1) A(15,2,1) A(16,2,1) A(17,2,1) A(18,2,1) A(19,2,1) A(20,2,1)

A(1,1,2) A(2,1,2) A(3,1,2) A(4,1,2) A(5,1,2) A(6,1,2) A(7,1,2) A(8,1,2) A(9,1,2) A(10,1,2)

A(511,512,113) A(512,512,113)

where the first index ix is assigned to the X coordinate, index iy is assigned to the Y coordinate and index iz is assigned to the Z coordinate in A(ix,iy,iz), and the first index runs faster than the second, and the second faster than the third. So when reading the matrix from the input file, A has the size [2962228 10] (the last row in the input file contains only two elements/columns).

I want to reshape this matrix into an equivalent Cartesian 3-D matrix, B(ix,iy,iz), of dimensions [nx ny nz] = [512 512 113] - is there an efficient way to do this? Also, 8 extra elements are appended in the last row when reading by fscanf() since A contains 10 elements per row - how do I not include these values when reshaping?

Many thanks in advance!!

Upvotes: 0

Views: 84

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

As discussed in comments, the following works:

B = A.'; % transpose to have the data in column-major order
B = B(1:end-8); % remove last values in linear order. Gives a column vector
result = reshape(B, [512 512 113]); % reshape to desired size

Upvotes: 1

Related Questions