[英]How to do PHP matrix operation easily and gracefully?
I've a $max
which is essentially a two dimensional array. 我有一个
$max
,它本质上是一个二维数组。
Each element in $max
is eithor 1
or 0
, $max
每个元素为1
或0
,
can be denoted by $max[$x][$y]
, where $x
is an integer within 0~WIDTH
,similar for $y
可以用
$max[$x][$y]
,其中$x
是0~WIDTH
的整数,与$y
类似
My purpose is to find rows and columns in the $max
that sums up greater than a CONSTANT
, and get the average distance
between rows/columns that qualify. 我的目的是在
$max
中查找总和大于CONSTANT
行和列 ,并获得符合条件的行/列之间的average distance
。
Anyone has a good solution ? 任何人都有一个好的解决方案?
I have not tested this, but it should work for summing up the columns and rows: 我没有对此进行测试,但是它应该适用于汇总列和行:
//Map columns and rows into their respective values
//Note that we preserve the col/row indexes
$rowval = array();
$colval = array();
foreach($max as $k1 => $row) {
$rowval[$k1] = array_sum($row);
foreach($row as $k2 => $col) {
if(!isset($colval[$k2])) {
$colval[$k2] = 0;
}
$colval[$k2] += $col;
}
}
//Define filter function
function is_over($val) {
return $val > CONSTANT;
}
//Filter out the cols/rows from their respective arrays
//Keys will be preserved by array_filter
$foundcols = array_filter($colval, 'is_over');
$foundrows = array_filter($rowval, 'is_over');
You still have to calculate the average distance though. 但是,您仍然必须计算平均距离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.