user2029767
user2029767

Reputation:

Nested if statement in for loop

So heres my script

function printPower

sum=0;
filename=input('Enter a filename: ','s');
power=load(filename);
for i=1:length(power);
    if power(i)>=0;    
        sum=sum+power(i);
    end
    TP=sum/24;
 end
 fprintf('Total power: %.1f kWh.\n', TP);

There are negative values in the text file im loading and I want it to only sum the positive ones but it still sums all values.

Upvotes: 0

Views: 148

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

You could just replace your loop with something like

total = sum(power(power>=0))/24

Personally I think that using the name of a Matlab intrinsic function, such as sum, as a variable name is just asking for trouble though I'm not sure it's caused a problem in your case. That's why the lhs of my statement is the variable total.

Upvotes: 1

Related Questions