# Adding numbers to an array

11 views (last 30 days)
Michael Eugene Carter on 3 Feb 2022
Answered: James Tursa on 3 Feb 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.

James Tursa on 3 Feb 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.