Adding numbers to an array

43 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by