Find the average in each row with certain conditions
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2017-2-5
" 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.
采纳的回答
Star Strider
2017-2-5
编辑:Star Strider
2017-2-5
‘... right column is lower than the one on the right ...’
Care to clarify that?
Sounds like homework.
This select the rows where Column #2 is greater than Column #1, takes the mean of those rows, and substitutes NaN for the ‘ignored’ rows. Make the appropriate changes to satisfy your requirements.
The Code:
N = 10;
A = rand(N,2);
Select_Rows = (A(:,2) - A(:,1)) > 0; % Select Rows With Col #2 > Col #1
Amean(Select_Rows,:) = mean(A(Select_Rows,:), 2);
Amean(~Select_Rows) = NaN;
3 个评论
Image Analyst
2017-2-5
Eduardo, note that this answer is different than mine. Not sure what you wanted but Star's answer gives Nans where the condition is true, while mine gives the mean as the value of the left column. It just depends on what you mean by "I have to ignore it" . I ignore the lower value and give the mean of what remains in the row, while Star's ignores the whole row. I think you wanted Star's interpretation (since you accepted it) but I just wanted to point out the differences in case you wanted means for all rows.
更多回答(1 个)
Image Analyst
2017-2-5
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!