write an m-file using while loop which calculates the sum of elements within the following vector x=[5 2 -9 10 -1 9 -1] until a number greater than 8 is met? please help i have tried and i am confused on how to do this.

i have tried and my codes don't work, how can i do this with a while loop?

2 comentarios

I assume this is a homework assignment. I suggest you post what you have tried and we can suggest where you went wrong.
s=[5 2 -9 10 -1 9 -1]
n=0;
a=0;
for n=s(1):s(6)
while sum(s)<=8
a=a+n;
sum(s)=a
end
end
% code
end

Iniciar sesión para comentar.

 Respuesta aceptada

x=[5 2 -9 10 -1 9 -1];
partialsum = 0;
i = 1;
while partialsum <= 8
partialsum = partialsum + x(i);
i = i + 1;
end

1 comentario

Perfect answer Thorsten, I was indeed summing the entire loop instead of summing incrementally. Thank you Thorsten and thanks to all, my problem is solved.

Iniciar sesión para comentar.

Más respuestas (1)

general outline would be
x=[5 2 -9 10 -1 9 -1];
while currentsum<=8
currentsum = %what you want to sum up.
end

2 comentarios

Thank you for your answer. When i run it, it just sums up the entire vector. It is supposed to stop summing at 5+2+(-9)+10+(-1)+9=16.
x=[5 2 -9 10 -1 9 -1];
while currentsum<=8
currentsum= sum(x)
end
% code
It returns 15 instead of 16.
"%what you want to sum up." should only be a subset of x, not all of x. Your loop should be incrementing the index of the last element that you are paying attention to. sum(x(1:SomeIndex)) and keep increasing SomeIndex. Make sure you stop when you reach the end of the array.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 6 de Oct. de 2015

Comentada:

el 6 de Oct. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by