Ben Fossen
Ben Fossen

Reputation: 1007

How do you sum values inside a for loop in Matlab?

I want to sum acidic as the for loop runs and then print out the total value of all the previous acidic values. My problem is right now is it is currently just printing the individual values not one summed value of acidic. How do I sum.

this is what is printing to the command window

ans =

5.9676

ans =

2.1676

here is my code

pki = [7.7,3.9];

t= 2;


n=55;

for i = 1:t;

    acidic = log10(1/((n-1)*(10^-pki(i))));

    sum(acidic)

end 

Upvotes: 0

Views: 42099

Answers (2)

mtrw
mtrw

Reputation: 35088

EDIT - As Donnie points out, you don't need the t variable.

You don't have a semicolon on your line sum(acidic), so MATLAB prints the result. But it looks like you have some other problems - acidic is a scalar, so the value is getting overwritten each time. Probably you want to do something like:

pki = [7.7,3.9];
n = 55;
acidic = log10(1./((n-1).*(10.^-pki)));

disp(sum(acidic))

Note the ./, .*, and .^ operators. These tell MATLAB to do element by element operations over the vectors. The last disp line tells MATLAB to print the output value.

Upvotes: 4

Donnie
Donnie

Reputation: 46913

sum() is for summing all of the values in a vector, or along an axis in a matrix. You don't need it with the way you have your code implemented. You could just do

pki = [7.7,3.9];
t= 2;
n=55;
acidic = 0;
for i = 1:t;
  acidic = acidic + log10(1/((n-1)*(10^-pki(i))));
end;

acidic

However, that's fairly inefficent matlab. What I would recommend doing is just calculating all of the values at once, and then use sum. You don't need the for statement if you do it this way:

pki = [7.7,3.9];
t= 2;
n=55;
acidic = log10(1 ./ ((n-1) .* (10 .^ -pki)));

sum(acidic)

Which does the calculation in one go. If you weren't always going to use all of pki, you could subscript into it, like so:

pki = [7.7,3.9];
t= 2;
n=55;
acidic = log10(1 ./ ((n-1) .* (10 .^ -pki(1:t))));

sum(acidic)

Upvotes: 6

Related Questions