How to add and array using a while loop

4 visualizaciones (últimos 30 días)
Andrew Matulich
Andrew Matulich el 19 de Mzo. de 2017
Respondida: Geoff Hayes el 20 de Mzo. de 2017
Im just confused on what to set the limiting number as.
function [] = matulich_c9p2(k)
k = [1,23,43,72,87,56,98,33];
while currentsum=413
currentsum=sum(k);
end

Respuestas (1)

Geoff Hayes
Geoff Hayes el 20 de Mzo. de 2017
Andrew - to test for equality (in your condition) you need to use two equal signs as
currents == 413
You use one equal sign for assignment as in
x = 42;
Though is this condition really what you want? Presumably, you have defined your currentsum as 413 before you enter the while loop (else the condition would never be satisfied) and you must be doing something more within this loop than what you have shown us.
Note that sum(k), where k is your array, finds the sum of all elements in your array...which is 413 and so your while condition is always satisfied and you will never exit the while loop.
You may want to provide more details about what you are attempting to do. Are you just trying to add up all consecutive numbers within an array until at least 413 is reached? Please clarify.

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