Matlab, comparing array using if statement

后端 未结 3 1596
猫巷女王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:17

    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.

提交回复
热议问题