Adding numbers to an array

82 visualizaciones (últimos 30 días)
Michael Eugene Carter
Michael Eugene Carter el 3 de Feb. de 2022
Respondida: James Tursa el 3 de Feb. de 2022
I am trying to create a while loop that calculates a number up to a certain point and then stops, but the problem that I am having is that the answer that I get needs to be in an array of each one of the consecutive numbers that were calculated. Right now though the final answer of the while loop only ends up being a single number. How would I go about adding the numbers into an array? I tried putting a for loop inside of the while loop but that didn't work properly and I can't find anything online that helps with this. This is the code that I have so far
h=1;
hnew=h/2;
while hnew>=1e-13
h=hnew;
hnew=h/2;
end
I know know that the array needs to be [1x45], but I 'm supposed to code it in a way that this would add to the array an unknown number of times.

Respuesta aceptada

James Tursa
James Tursa el 3 de Feb. de 2022
You don't really need both h and hnew. Just use h and some indexing. E.g.,
h = zeros(1,45); % allocate expected result
k = 1; % first index
h(k) = 1; % first value
while h(k) > 1e-13 % while current value is too big
h(k+1) = _____; % Calculate next value ... I will leave this for you to figure out
k = k + 1; % increment index
end
h = h(1:k); % clip result in case we need to
I've included the indexing scheme to get your array, but still left some work for you to do.

Más respuestas (0)

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by