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

15 ビュー (過去 30 日間)
Mads Andersen
Mads Andersen 2019 年 3 月 6 日
回答済み: tmarske 2019 年 3 月 6 日
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? :)

採用された回答

Torsten
Torsten 2019 年 3 月 6 日
sum(max(A,0),2)

その他の回答 (2 件)

Image Analyst
Image Analyst 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?

tmarske
tmarske 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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by