Matlab comparing an array using an if statement

I searched the web trying to find the answer to this problem.

I have an array similar to the following

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

From these values ​​I want to create a median map. So I created an array

 MedianMap = int8(zeros(MAX_ROWS, MAX_COLS)) 

Inside this array, I want to assign three different values: 1, 0, -1. Thus, the average output of the card will have the same size of the array "A":

  • if the value is greater than the median row and column, the symbol "1" is assigned to the median of the map
  • if the value is less than the average and the column median, the symbol "-1" is assigned to the median of the map
  • otherwise a 0?

How can I go through each row and column in array “A” and associate it with my corresponding column and middle row of the row?

I wrote the code in C code and it was successful, however it just fought in Matlab.

+4
source share
3 answers

Here's how I do it:

  • Create logical indexes for each condition (item is larger / smaller than average / average)
  • Use logical indexes 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 extends row_median and col_median to arrays of the same size as A
  • A > yMedian returns a matrix of the same size as A , containing the logical results of comparing each element of A with the corresponding xMedian element.
  • isRowHigh & isColHigh performs elementary AND from boolean matrices
  • MedianMap(L) , where L is a logical index (Boolean matrix), selects the MedianMap elements corresponding to the L elements that are true.
+1
source

Here's how I would do it:

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

This is multi-threaded (suitable for much larger problems) and does not have any of the temporary elements involved in other answers (a much smaller memory peak).

It's not very pretty, though :) So, if you have better readability, 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 single 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 ); 
+1
source
 MedianMap = (A > Rmedian'*ones(1,4))+ ( A > ones(3,1)*Cmedian) -1 
-1
source

Source: https://habr.com/ru/post/1437311/


All Articles