Hi Kostas,
It seems like you're trying to reshape a 3D matrix into a block-diagonal matrix on its 2nd dimension. The issue you're encountering is due to the incorrect calculation of linear indices for the new matrix.
You can try the following code which uses a loop over the third dimension of your matrix ‘M’. This code will create a block-diagonal structure where each block comes from the corresponding 2D slice of ‘M’. It's not using ‘blkdiag’ function, thus it should be faster.
clear ; clc
v = 1:3672 ;
Nc = 18 ; % Rows
Nb = 4 ; % Columns
nn = 51 ; % Pages
M = reshape(v, Nc, Nb, nn) ; % 3D matrix which contains experimental data in my case
Mn = zeros(Nc, Nc*Nb, nn) ; % Preallocated new matrix with extended number of columns
for k = 1:nn
for i = 1:Nc
Mn(i, ((i-1)*Nb+1):i*Nb, k) = M(i,:,k);
end
end
This code will create a new matrix ‘Mn’ where each row of each 2D slice of ‘M’ is placed on the diagonal of the corresponding 2D slice of ‘Mn’.
If you face performance issues with this code, you might need to consider using a sparse matrix representation or other optimization techniques.
Refer to the following MATLAB Documentation Link to know more about ‘blkdiag’ function:
Hope the above solution helps you.
Best Regards,
Aman Banthia