Sum all negative values in a matrix

조회 수: 7 (최근 30일)
Kimberly S
Kimberly S 2015년 6월 1일
편집: John D'Errico 2015년 6월 1일
I have a matrix that is 400x95. I would like to sum all the negative values in each column and divide this by the sum of all the positive values in the same column to yield a new vector that is essentially 1x95. Any help is much appreciated!

채택된 답변

John D'Errico
John D'Errico 2015년 6월 1일
편집: John D'Errico 2015년 6월 1일
Too trivial?
sum(A.*(A < 0),1)./sum(A.*(A > 0),1)
The point is, to learn to start to think in terms of matrices and vectors, and operations on those objects.
Of course, be careful if there are no positive elements in a column of the array. In that case, you will get either an Inf or NaN result, depending on if there are any negative values in that column.
  댓글 수: 2
Joseph Cheng
Joseph Cheng 2015년 6월 1일
2nd method would used the 2nd input parameter in max() and min().
x = magic(10)-50;
rat = sum(min(x,0))./sum(max(x,0))
John D'Errico
John D'Errico 2015년 6월 1일
Another good way. There are always so many ways to solve a problem like this, once you start thinking in terms of arrays.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by