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 Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by