Automating the amount in an array

I will try to explain the problem associated with this code.

This script works well for up to three people ($ numRows = 3).

$z=0;
$i=0;
$x=0;

do {
    $total[] = (
        ${'contaH'.$z}[$i+0]*$final[$x+0]+
        ${'contaH'.$z}[$i+1]*$final[$x+1]+
        ${'contaH'.$z}[$i+2]*$final[$x+2]
    );
    $z++;
} while ($z<$numRows); //3

But if I have only four people ($ numRows = 4), I need something like this:

$z=0;
$i=0;
$x=0;

do {
    $total[] = (
        ${'contaH'.$z}[$i+0]*$final[$x+0]+
        ${'contaH'.$z}[$i+1]*$final[$x+1]+
        ${'contaH'.$z}[$i+2]*$final[$x+2]+
        ${'contaH'.$z}[$i+3]*$final[$x+3]
        // if they are 5 persons ($numRows=5), here, should exists another row
    );
    $z++;
} while ($z<$numRows); //4

So the problem is automating these changes with respect to $ numRows.

Here is the diagram of matrix algebra:

Enter image description here

The only thing I want is the dynamic code of my code as a function of the number of people.

A   |  B |  C |  D
Person1
Person2
Person3
Person4
...

In my case, it can be different - it's just the number of people.

More info here .

+5
source share
3 answers
$z=0;
$i=0;
$x=0;
$numRows = 5;

do{
    $currentSum = 0;
    for($c = 0; $c < $numRows; $c++){
        $currentSum += (${'contaH'.$z}[$i+$c] * $final[$x+$c]);
    }
    $total[] = $currentSum;
    $z++;
}while($z < $numRows);
+2
source
$subtotal = 0;
for ($i = 0; $i < $numRows; $i++) {
   $subtotal += ${'contaH'.$z}[$i] * $final[$i];
}
$total[] = $subtotal;
0
source

Math_Matrix, .

, , :

function mat_mult($matrix, $vector) {
    $result = array();
    $matrixWidth = count($matrix[0]);
    for ($z = 0; $z < $matrixWidth; $z++) {
        $value = 0;
        for ($y = 0; $y < $matrixWidth; $y++) {
            $value += $matrix[$z][$y]*$vector[$y];
        }
        $result[] = $value;
    }
    return $result;
}

$matrix = array(
    array(1, 1/3.0, 2, 4),
    array(3, 1, 5, 3),
    array(1/2.0, 1/5.0, 1, 1/3.0),
    array(1/4.0, 1/3.0, 3, 1)
);
$vector = array(0.26, 0.50, 0.09, 0.16);

$v2 = mat_mult($matrix, $vector);

print_r($v2);

, :

$matrix = array();
for ($z = 0; $z < $numRows; $z++) {
    $matrix[] = ${'contaH'.$z};
}
0
source

All Articles