Matlab:如何在指定维度上裁剪数组iff,其中所有值都等于指定值

时间:2017-08-26 18:54:58

标签: matlab multidimensional-array

在Matlab中,我正在寻找一种以更优雅的方式解决以下问题的方法: 在三维数组中,在一个维度上(即在我的情况下是时间),从所有值的某个索引等于零,例如,以下示例数组a为0表示第二维的索引为3(即a(:,3:end,: == 0)):

a(:,:,1) =

 1     1     0
 1     0     0
 1     0     0


a(:,:,2) =

 1     1     0
 1     0     0
 1     1     0


a(:,:,3) =

 1     1     0
 1     1     0
 1     1     0

[编辑,被要求预期结果]

预期结果是:

o(:,:,1) =

     1     1
     1     0
     1     0


o(:,:,2) =

     1     1
     1     0
     1     1


o(:,:,3) =

     1     1
     1     1
     1     1 

现在我当然可以检查维度2中的每个索引,到处都是零,这就是我现在正在做的事情,但我觉得有一些更好的方法可以在matlab中解决这个问题一些更优雅的方式(甚至可能对任何多维数组)。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

function req = removeColwithSpecVal(a,spec_val)
  req=num2cell(a,[1 2]);     %Converting to cell keeping the order of rows & columns same  
  req=vertcat(req{:});       %Stacking multidimensional slices vertically
  ind= ~all(req==spec_val,1);%Finding logical indices of the required columns
  req = req(:,ind);          %The matrix after removal of the not required columns
  %Finding the size of the input matrix 'a'; stacking with 1 so that 
  %it is applicable on 1-D/2-D matrices as well
  sz =[size(a) 1];           
  %Finding the # of columns that the required multi-dimensional matrix will have
  sz(2)= numel(req)/prod([sz(1), sz(3:end)]);
  %Reshaping to the desired result
  req=reshape(permute(reshape(req.', sz(2),sz(1),[]),[2 1 3]),sz); 
end

示例运行

%1-D Example
spec_val=5;
a=[1 4 5 2 5];
req = removeColwithSpecVal(a,spec_val)

req =

     1     4     2

%2-D Example
spec_val=0;
a=[1  1  0 ;
   1  0  0 ;
   1  0  0 ];
req = removeColwithSpecVal(a,spec_val)

req =
      1     1
      1     0
      1     0

%Your example (3-D)
spec_val=0;
a(:,:,1) = [1  1  0;
            1  0  0;
            1  0  0];
a(:,:,2) = [1  1  0;
            1  0  0;
            1  1  0];
a(:,:,3) = [1  1  0;
            1  1  0;
            1  1  0];
req = removeColwithSpecVal(a,spec_val)

req(:,:,1) =

     1     1
     1     0
     1     0


req(:,:,2) =

     1     1
     1     0
     1     1


req(:,:,3) =

     1     1
     1     1
     1     1

也适用于高维矩阵。