Matlab, comparing array using if statement

后端 未结 3 1597
猫巷女王i
猫巷女王i 2021-01-19 10:04

I have searched the net trying to find an answer to this problem I have.

I have an array much like the following

A = [2 4 6 8 ; 3 5 7 9 ; 1 4 6 9]

r         


        
3条回答
  •  心在旅途
    2021-01-19 10:29

    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 ); 
    

提交回复
热议问题