MATLAB,使用if语句比较阵列 [英] Matlab, comparing array using if statement
问题描述
我已搜查了净试图找到一个答案,这个问题我有。
I have searched the net trying to find an answer to this problem I have.
我有一个数组很像以下
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))
在这阵我要分配三个不同的值:1,0,-1。这样的中位图输出将阵列的A的大小相同:
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':
- 如果该值大于两行和列中值较大的一个1被分配给该位映射
- 如果该值小于两行和列中值-1被分配给该位映射
- ,否则为0?
我怎么能每行每列遍历了A数组中,它涉及到其各自的列和行中位数?
How can I traverse through every row and column in the "A" array and relate it to its respective column and row median?
我已经写在C code中的code,它是SUCESSFUL,但只是在Matlab中挣扎。
I have written the code in C code and it was sucessful, however just struggling in Matlab.
推荐答案
下面是我会怎么做:
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).
这不是很pretty虽然:)所以,如果有更好的可读性是你以后,使用 meshgrid
在BrianL的回答,或 repmat
:
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 );
或由那些矩阵为RASMAN做乘法:
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 );
这篇关于MATLAB,使用if语句比较阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!