MATLAB:访问多维单元矩阵索引

时间:2016-10-15 13:26:15

标签: matlab multidimensional-array indexing

我有单元格矩阵,其尺寸根据用户输入而变化。作为用户,我想使用一维的特定索引,同时存在其他维度的整体元素。我认为最好用一个例子来解释这种情况:
假设我的单元格矩阵A的大小为2x3x4x5x7。我想使用1.3.4. dimension的整个元素。同时仅2. element的{​​{1}}和2. dimension 3., 5. elements。这可以通过以下方式轻松实现:

5. dimension

案例A如何输入函数且尺寸正在变化。如何通过线性索引或其他方式获得此结果? 我知道没有这样的语法,但我的情况可以描述如下:

A(:,2,:,:,[3 5]);

1 个答案:

答案 0 :(得分:0)

使用以下代码可以解决此问题:

size_A          = size(A); % A is the matrix whose elements will be selected
whole_index     = cellfun(@(x) 1:x,num2cell(size_A),'UniformOut',false); % create a cell array which includes all the possible numbers
all_sizes       = cellfun(@length,whole_index); % each dimension size
%% select the desired indexes in your desired dimensions
whole_index{1}  = [1 2]; % first dimension first 2 elements
whole_index{2}  = [2];   % second dimension second element
all_numbers     = combvec(whole_index{:}).'; % whole possibilities
all_numbers     = mat2cell(all_numbers,max(size_nums),ones(1,min(size_nums))); % cell format of possibilities
comb_inds       = sub2ind(all_sizes,all_numbers{:}); 
desired_out     = A(comb_inds);

另一种解决方案如下:

    size_A          = size(A); % A is the matrix whose elements will be selected
    whole_index     = cellfun(@(x) 1:x,num2cell(size_A),'UniformOut',false); 
    %% select the desired indexes in your desired dimensions
    whole_index{1}  = [1 2]; % first dimension first 2 elements
    whole_index{2}  = [2];   % second dimension second element
    desired_out     = A(whole_index{:});