Borrar filtros
Borrar filtros

I need to add numbers in an array using a for loop...plz help

19 visualizaciones (últimos 30 días)
Brian C
Brian C el 12 de Nov. de 2015
Respondida: bio lim el 12 de Nov. de 2015
Say i have array of [1;2;3] and want to sum it, the answer should be 6. im not allow to use Matlab sum function to get the sum ex. sum(A)
Here's what I have
A=[1;2;3]; b=length(A);
sum=0; for i=1:b
sum= sum+i;
end
disp(sum)
Not sure if i am going about this the wrong way. believe my sum=sum+i line is the issue?

Respuestas (1)

bio lim
bio lim el 12 de Nov. de 2015
The problem with your code is sum = sum + i. Your i is defined as i = 1:b = 1:length(A). You are summing the index numbers of your column vector rather than the element of each row. In order words, no matter what element you define in your column vector, as long as the size is maintained (in your case, 3), you will always get the same answer 6. What you need to do is define sum = sum + A(i).
A=[1;2;3]; b=length(A);
sum=0; for i=1:b
sum= sum+A(i);
end
disp(sum)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by