### Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

## How to sum all positive values in each row in matrix?

さんによって質問されました 2019 年 3 月 6 日

### tmarske (view profile)

さんによって 回答されました 2019 年 3 月 6 日
Torsten

### Torsten (view profile)

さんの 回答が採用されました
Hello.
I have a 8760x10 matrix where i want to sum all positive numbers in each row seperatly to yield a new 8760x1 vector with the sum of all positive values from each row. normally if i would do it on a single vector then i would just use:
sum(d(d>0))
but i dont know how to do it within a loop and for many rows
Here is what i got so far:
for i = 1:n
central(i) = sum(prod((i),(1:6)))+sum(prod((i),(12:17)))+sum(prod((i),(20:25)))+sum(prod((i),(93:100)));
decentral(i) = sum(prod((i),(7:11)))+sum(prod((i),(18:19)))+sum(prod((i),(26:92)));
solar(i) = sum(renew((i),(1:12)));
hydro(i) = renew(i,13);
wind(i) = sum(renew((i),(14:78)));
netimport(i) = sum(inter((i),(1:7)))+sum(inter((i),(9:10)));
if netimport(i) < 0
netimport(i) = 0;
elseif netimport(i) > 0
totalimport(i) = sum(inter(i)(inter(i)>0)); % this is the line i dont know how to do. it should be able to sum all positive numbers in all 8760 seperatly.
% another idea that i have had was:
totalimport(i) = sum(inter((i),(1:10))(inter((i),(1:10))>0));
Anybody that can help? :)

#### 0 件のコメント

サインイン to comment.

## 3 件の回答

### Torsten (view profile)

2019 年 3 月 6 日
採用された回答

sum(max(A,0),2)

#### 0 件のコメント

サインイン to comment.

### Image Analyst (view profile)

2019 年 3 月 6 日

sum(d(d>0))
would sum all values in the matrix and give you a single number, NOT the sum of rows. You'd want
dCopy = d;
dCopy(d <= 0) = 0;
% Sum along columns to give a sum for every row.
columnVectorSums = sum(dCopy, 2);
Why would you want to do it via a for loop?

#### 0 件のコメント

サインイン to comment.

### tmarske (view profile)

2019 年 3 月 6 日

Firstly, I assume that prod is either a function you have written or a variable you created? If so it's overwriting the matlab builtin function prod. This is something you generally want to avoid doing and I'd strongly suggest you pick a different name for this function/variable.
Returning to your question, you can do:
sum(max(d, 0), 2)
for example:
>> aa = magic(6)-15
aa =
20 -14 -9 11 4 9
-12 17 -8 6 8 10
16 -6 -13 7 12 5
-7 13 18 2 -5 0
15 -10 19 -3 -1 1
-11 21 14 -2 3 -4
>> sum(max(aa, 0), 2)
ans =
44
41
40
33
35
38

#### 0 件のコメント

サインイン to comment.

Translated by