How to extract hyperspace of a n dimensions matrix

4 次查看(过去 30 天)
Hi,
I working with a matrix M with currently 9 dimensions array. I want to extract the submatrix of let say the 1st element of the 6th dimension. The answer is obviously subM = squeeze(M(:,:,:,:,:,1,:,:,:));
The problem is that the number of dimension of my matrix M is variable, so is there any generic way to extract a specific hypermatrix (i.e for a n dimension matrix, extract the i-th element of the m-th dimension giving a n-1 dimension submatrix)

回答(1 个)

Prateekshya
Prateekshya 2024-9-4
Hello Renaud,
You can take the help of indexing cell array to perform extraction of hyperspace from a multi-dimensional matrix. Let us take a 5-dimensional matrix and see how it works:
% Define the size of each dimension
dim1 = 3;
dim2 = 4;
dim3 = 5;
dim4 = 6;
dim5 = 7;
% Generate grid data for each dimension
[x1, x2, x3, x4, x5] = ndgrid(1:dim1, 1:dim2, 1:dim3, 1:dim4, 1:dim5);
% Create a 5D matrix with a specific pattern
% For example, use a simple function: M = x1 + 2*x2 + 3*x3 + 4*x4 + 5*x5
M = x1 + 2*x2 + 3*x3 + 4*x4 + 5*x5;
% Specify the dimension and the index to extract
m = 3; % The dimension to slice
i = 2; % The index to extract from the m-th dimension
% Determine the number of dimensions in M
numDims = ndims(M);
% Create an indexing cell array
index = repmat({':'}, 1, numDims); % Initialize with ':'
index{m} = i; % Set the specific index for the m-th dimension
% Extract the submatrix
subM = squeeze(M(index{:}));
% Display the size of the original and submatrix
disp('Original matrix size:');
disp(size(M));
disp('Submatrix size:');
disp(size(subM));
% Display the submatrix for verification
disp('Extracted submatrix:');
disp(subM);
You can modify the matrix generation part, add your data directly and follow the further process to extract the hyperspace.
I hope this resolves your query!

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by