Find the average in each row with certain conditions

조회 수: 5 (최근 30일)
Eduardo Alfaro
Eduardo Alfaro 2017년 2월 5일
댓글: Image Analyst 2017년 2월 5일
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
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
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
Star Strider
Star Strider 2017년 2월 5일
No worries.
I guessed correctly!
Image Analyst
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
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.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by