Adding numbers to an array

75 次查看(过去 30 天)
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
James Tursa 2022-2-3
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by