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]
row median = [ 5 6 5 ]
col median = [ 2 4 6 9 ]
From these values I want to create a median map. So I have created the array
MedianMap = int8(zeros(MAX_ROWS, MAX_COLS))
Within this array I want to assign three different values: 1, 0, -1. So the median map output will be of the same size of array 'A':
- if the value is greater than both the row and column median a "1" is assigned to the median map
- if the value is less than both the row and column median a "-1" is assigned to the median map
- otherwise a 0?
How can I traverse through every row and column in the "A" array and relate it to its respective column and row median?
I have written the code in C code and it was sucessful, however just struggling in Matlab.
Here is how I would do it:
- Create logical indices for each condition (element greater/less than row/col median)
- 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
expandsrow_median
andcol_median
into arrays of the same size asA
A > yMedian
returns a matrix of the same size asA
containing the boolean results of comparing every element ofA
with the corresponding element ofxMedian
.isRowHigh & isColHigh
performs an element-wise AND of the boolean matricesMedianMap(L)
, whereL
is a logical index (boolean matrix), selects the elements ofMedianMap
corresponding to the elements ofL
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
来源:https://stackoverflow.com/questions/12683393/matlab-comparing-array-using-if-statement