Matlab, comparing array using if statement

╄→尐↘猪︶ㄣ 提交于 2019-12-01 18:46:54

Here is how I would do it:

  1. Create logical indices for each condition (element greater/less than row/col median)
  2. Use the logical indices to update MedianMap.

In code:

[xMedian, yMedian] = meshgrid(col_median, row_median);

isRowHigh = (A > yMedian);
isColHigh = (A > xMedian);

isRowLow = (A < yMedian);
isColLow = (A < xMedian);

MedianMap(isRowHigh & isColHigh) = 1;
MedianMap(isRowLow & isColLow) = -1;

Notes:

  • meshgrid expands row_median and col_median into arrays of the same size as A
  • A > yMedian returns a matrix of the same size as A containing the boolean results of comparing every element of A with the corresponding element of xMedian.
  • isRowHigh & isColHigh performs an element-wise AND of the boolean matrices
  • MedianMap(L), where L is a logical index (boolean matrix), selects the elements of MedianMap corresponding to the elements of L which are true.

Here's how I would do that:

MedianMap = ...
    ( bsxfun(@gt,A,col_median) & bsxfun(@gt,A,row_median.') ) - ...
    ( bsxfun(@lt,A,col_median) & bsxfun(@lt,A,row_median.') );

This one is multi-threaded (suited for much larger problems) and doesn't have any of the temporaries involved in the other answers (much smaller peak memory footprint).

It's not very pretty though :) So if better readability is what you're after, use either meshgrid as in BrianL's answer, or repmat:

Col_median = repmat(col_median, size(A,1),1);
Row_median = repmat(row_median.', 1, size(A,2));

MedianMap = ...
    ( A > Col_median & A > Row_median ) - ... 
    ( A < Col_median & A < Row_median ); 

or multiplication by a ones-matrix as Rasman did:

Col_median = ones(size(A,1),1) * col_median;
Row_median = row_median.' * ones(1,size(A,2));

MedianMap = ...
    ( A > Col_median & A > Row_median ) - ... 
    ( A < Col_median & A < Row_median ); 
MedianMap  = (A > Rmedian'*ones(1,4))+ ( A > ones(3,1)*Cmedian) -1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!