MATLAB: Count number of values within a range in matrix per column and assign count to new matrix

conditional countingelement countMATLABmatrix

Hi everyone. I'm using R2017b to work with a large matrix. The matrix is the result of calculating the value of an equation while looping through coefficients (and interpolating between coefficients) representing the 95% CI.
What I would like to do is:
1. Count the number of elements that fall under certain range on a per column basis (say, elements between 0 and 0.5)
2. Assign that count to an element of a different matrix
3. Repeat steps 1 and 2 using a new range (say, elements between 0.5 and 1.0)
4. Repeat steps 1 through 3 for all columns
Example:
Count values between 0 and 0.5, and 0.5 and 1.0 in matrix A and assign the results to matrix B
A= [
0.83 0.02
NaN 0.69
0.7 0.72
0.3 0.32
NaN 0.8
0.02 0.04
0.56 NaN
0.78 NaN
0.01 0.03
0.67 NaN];
B =
3 4 %% Number of elements that satisfy the first condition
5 3 %% Number of elements that satisfy the second condition
Hope you can help. Cheers!

Best Answer

This will do it:
A= [
0.83 0.02
NaN 0.69
0.7 0.72
0.3 0.32
NaN 0.8
0.02 0.04
0.56 NaN
0.78 NaN
0.01 0.03
0.67 NaN]
[ra, ca] = size(A)
ranges = [0, 0.5;
0.5, 1]
[rr, cr] = size(ranges);
B = zeros(rr, ca)
for row = 1 : rr
B(row, :) = sum(A > ranges(row, 1) & A <= ranges(row, 2), 1)
end
Just a simple for loop that should be easy to understand.
A > ranges(row, 1) & A <= ranges(row, 2) is a binary matrix that says how many elements are in that particular range. 1 if it's in the range and 0 if it's not in the range.
Then sum() just sums them up in each of the columns and the two column sums are assigned to a row in B.