【问题标题】:Why is my logical mask not working on a 2D matrix in matlab properly?为什么我的逻辑掩码不能正确处理 matlab 中的二维矩阵?
【发布时间】:2017-09-02 05:44:10
【问题描述】:
X(100,371) 
%% contains 100 datapoints for 371 variables

我只想保留均值+标准差范围内的数据:均值-标准差。

我是这样处理的:

mx=mean(X);sx=std(X);      
%%generate mean, std 
%%this generates mx(1,371) and sx(1,371)

mx=double(repmat(mx,100,1));
%%this fills a matrix with the same datapoints, 
%%100 times
sx=double(repmat(sx,100,1));
%% this gives mx(100,371) and sx(100,371)


g=X>mx-sx & X<mx+sx;        
%%this creates a logical mask g(100,371)
%%filled with 1s and 0s 

test(g)=X(g);               
%%this should give me test(100,371), but I get 
%%test(37100), which is wrong as it doesnt maintain 
%%the shape of X

test=reshape(test,100,371)  
%% but when I compare this to the my original matrix
%% X(100,371) I hardly see a difference (datapoints 
%% in test are still outside the range I want.

我做错了什么?

【问题讨论】:

    标签: matlab indexing binary mask


    【解决方案1】:

    这行代码有一点语法问题

    test(g) = X(g);
    

    当编译器执行X(g) 时,它返回Xg 表示1 的所有元素,并在执行test(g) 时创建一个test 变量,其大小足以满足由g 索引,即 1x37100,然后将所有元素分配到正确的位置。长话短说,在分配之前,您可以添加以下内容:

    test = zeros(size(X));
    

    此时,您可以使用 bsxfun 来获取逻辑索引,而无需执行 repmat

    g = bsxfun(@gt,X,mx - sx) & bsxfun(@lt,X,mx + sx)
    

    在 R2016b 或最近有隐式 bsxfun 扩展

    g = X > mx - sx & X < mx + sx
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 2014-04-10
      • 1970-01-01
      相关资源
      最近更新 更多