MATLAB: How to correctly use two “for loops” and one “if statement” to insert selected data into a cell array

for loopif statement

I have the following variables: Matrix A with the size 75×1, Matrix B with the size 2400×2, Cell C with the size 75×1.
I am trying to insert B(i,2) into C{j}, if it passes the condition (A(j,1)-0.25)<B(i,1)<(A(j,1)+0.25). I am doing this so that later I can take the averages of each element of C. The code I have written for this is not working the way it should. It puts all the elements of B(:,2) into each cell of C. Any help would be appreciated. Thanks in advance!
C = cell(75,1);
for i = 1:75
for j = 1:2400
if (A(i,1)-0.25) < B(j,1) < (A(i,1)+0.25)
C{i}(end+1)= B(j,2);
end
end
end
D = cell(size(C));
for o = 1:numel(D)
D{o} = mean(C{o});
end
D = cell2mat(D);

Best Answer

The correct way to do what you want is not to use loops and if statements but operate on whole matrices at once. It will be a lot faster.
However, the only reason your code does not work is because:
x < y < z
is not the way you write comparison in matlab (and most computer languages). The correct way is
x < y && y < z
What you have written compares x to y. That produces one of two results, either 0 (false) or 1 (true). It then compares that 0 or 1 result to z. Hence, if z is greater than 1, then your test will always return true regardless of the value of x and y.
But, as said, the best way to do what you want, assuming R2016b or later:
inrange = abs(B(:, 1)' - A) < 0.25; %compare all of B with all of A at once
D = sum(inrange .* B(:, 2)', 2) ./ sum(inrange, 2);
If on earlier than R2016b:
inrange =abs(bsxfun(@minus, B(:, 1)', A)) < 0.25;
D = sum(bxsfun(@times, inrange, B(:, 2)'), 2) ./ sum(inrange, 2);