Find the average in each row with certain conditions
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Eduardo Alfaro
el 5 de Feb. de 2017
Comentada: Image Analyst
el 5 de Feb. de 2017
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 comentario
Image Analyst
el 5 de Feb. de 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.
Respuesta aceptada
Star Strider
el 5 de Feb. de 2017
Editada: Star Strider
el 5 de Feb. de 2017
‘... 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 comentarios
Image Analyst
el 5 de Feb. de 2017
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.
Más respuestas (1)
Image Analyst
el 5 de Feb. de 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.
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!