Matlab:如何从指定维度裁剪数组,如果数组中的所有值都等于指定值

Matlab:如何从指定维度裁剪数组,如果数组中的所有值都等于指定值,matlab,multidimensional-array,Matlab,Multidimensional Array,在Matlab中,我正在寻找一种更优雅的方法来解决以下问题: 在三维数组中,在一维上(即在我的例子中是时间),从某个索引开始,所有值都等于零,例如,以下示例数组a为0,第二维的索引为3(即a(:,3:end,:==0)): [编辑,询问预期结果] 预期结果是: o(:,:,1) = 1 1 1 0 1 0 o(:,:,2) = 1 1 1 0 1 1 o(:,:,3) =

在Matlab中,我正在寻找一种更优雅的方法来解决以下问题: 在三维数组中,在一维上(即在我的例子中是时间),从某个索引开始,所有值都等于零,例如,以下示例数组a为0,第二维的索引为3(即
a(:,3:end,:==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中有更好的方法以更优雅的方式解决这个问题(甚至可能对任何多维数组)。谢谢你的帮助

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

也适用于高维矩阵。

那么您的预期输出是……?感谢您的提及,现在编辑将考虑该问题。是否要删除所有零/其他特定值的相同列?是的,确实如此。更棒的当然是解决任意维度问题的解决方案。我想你的第一句话在什么地方被打断了,我不明白你想达到什么目的。你能包括你当前的代码吗?
%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