Find the average in each row with certain conditions
Show older comments
I have a Nx2 array and have to find the average of each row. However, if the number in the right column is lower than the one on the left, I have to ignore it in the calculation. No if statements allowed.
1 Comment
Image Analyst
on 5 Feb 2017
" the number in the right column is lower than the one on the right" <=== Huh??? Maybe you should just use column 1 and column 2 to remove the ambiguity.
Accepted Answer
More Answers (1)
Image Analyst
on 5 Feb 2017
Not sure what your ambiguous statement about which columns to compare means, but here is one interpretation:
% Create sample data
numRows = 8;
m = randi(9, numRows, 2)
% See if column 1 is greater than or equal to column 2:
badRows = m(:, 1) > m(:, 2)
% Zero out the bad elements in column 2
mCopy = m; % Let's not change our original m
mCopy(badRows, 2) = 0;
% Sum horizontally
rowSums = sum(mCopy, 2)
% Compute the number of items we're summing in each row
rowCounts = 2 - badRows
% Compute the sums
theMeans = rowSums ./ rowCounts
Note, it could be made shorter by eliminating comments (rarely a good idea) and combining some lines, or using cryptic one-liners like arrayfun(), but I thought a very explicitly spelled out code like this would be most helpful to a beginner like you.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!