Adding numbers to an array

조회 수: 82 (최근 30일)
Michael Eugene Carter
Michael Eugene Carter 2022년 2월 3일
답변: James Tursa 2022년 2월 3일
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