2016-10-15 108 views
0

我有單元矩陣,其尺寸根據用戶輸入而改變。作爲一個用戶,我想使用一維的特定索引,同時整個其他維度的元素都存在。我認爲最好用一個例子來解釋一下情況:
假設我的單元矩陣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) 

回答

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