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

我有单元矩阵,其尺寸根据用户输入而改变。作为一个用户,我想使用一维的特定索引,同时整个其他维度的元素都存在。我认为最好用一个例子来解释一下情况:
假设我的单元矩阵A的大小为2x3x4x5x7。我想要使​​用整个元素1.,3.4. dimension。同时只有2. dimension3., 5. elements2. element5. dimension。这可以通过以下方式轻松实现:MATLAB:访问多维单元矩阵索引

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

情况A是输入功能和尺寸是否发生变化。我怎样才能用线性索引或其他方式获得这个结果? 我知道有没有这样的语法,但我的情况可以描述如下:

whole_indexes = sub2ind(size(A),[:,2,:,:,[3,5]]); 

A(whole_indexes)

回答:

这个问题是可以解决的与下面的代码:

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{:});

以上是 MATLAB:访问多维单元矩阵索引 的全部内容, 来源链接: utcz.com/qa/257357.html

回到顶部