# Putting a Count function for a matrix, in a loop

previously i had a doubt on how to assign different rows with certain values using a special function, which i later figured out by using the far more superior "DO" Loop. At present i have two matrices c and d as shown below

dv = 1/2;
c = ( {
{0 dv, 0},
{1 dv, 0},
{2 dv, 0},
{3 dv, 0}
} );
d = ( {
{0.11, 0},
{0.35, 0},
{0.17, 0},
{0.99, 0}
} );
Do[Do[c[[i, 2]] =
Count[{d[[j, 1]]}, Between[d[[j, 1]], {(i - 1)*dv, (i)*dv}]], {i,
1, 4}], {j, 1, 4}];
MatrixForm[c]


so the output is -MatrixForm[{{0, 0}, {1/2, 0}, {1, 0}, {3/2, 0}}] but it should have been

MatrixForm[{{0, 3}, {1/2, 1}, {1, 0}, {3/2, 0}}]


i suspect the problem is in the "Between" function(maybe it is not a good equivalent of saying x lies between this and that). How do i rectify my code to get the desired output?(output explained= as 0.11,0.35 and 0.17 are lesser than 0.5 they belong to the ith row 2nd column where i is 1. Similarly 0.99 belongs to the 2nd row as it is less than 2dv-> that is 1 .)

Minimal changes to your code: (1) To increment c[[i, 2]] you need to use c[[i, 2]] += .. and (2) the second argument of Count should be a pattern:

Do[Do[c[[i, 2]] += Count[{d[[j, 1]]}, _?(Between[#, {(i - 1)*dv, (i)*dv}] &)], {i, 1,
4}], {j, 1, 4}];

MatrixForm[c]


You can use Boole[Between[...]] instead of Count[...]:

Do[Do[c[[i, 2]] += Boole@Between[d[[j, 1]], {(i - 1)*dv, (i)*dv}], {i, 1, 4}], {j, 1, 4}];


Using a single do loop instead of two:

c = ({{0 dv, 0}, {1 dv, 0}, {2 dv, 0}, {3 dv, 0}});

Do[c[[i, 2]] = Count[d[[All, 1]], _?(Between[#, {(i - 1)*dv, (i)*dv}] &)], {i, 1, 4}]

c

 {{0, 3}, {1/2, 1}, {1, 0}, {3/2, 0}}


Alternative ways to get the same result without loops:

MapIndexed[{#[[1]], Length@
Select[Function[x, (#2[[1]] - 1)*dv <= x <= #2[[1]]*dv]][d[[All, 1]]]} &, c]

MatrixForm @ %


Transpose[{c[[All, 1]],
Table[Count[d[[All, 1]], _?(Between[#, {(i - 1)*dv, (i)*dv}] &)], {i, 4}]}]

 {{0, 3}, {1/2, 1}, {1, 0}, {3/2, 0}}


etc...