Hi, i'm having trouble getting my answer in the from of an array when calling a previously defined function inside a for loop. Am i calling or defining the counting varibale wrong or am i not calling it in the right places. Please help.
function times = timeLoop(startVelocity, distance)
for i = (1:length(startVelocity))
times = fallTime(startVelocity(i), distance(i));
end
end
call using times = timeLoop([2, -3, 5],[100, 150, 300])
supposed to get times = 4.3160 5.8443 7.3275
keep getting times = 7.3275

回答 (1 件)

madhan ravi
madhan ravi 2020 年 10 月 9 日

0 投票

Note: Never name a variable times.
function TimeS = timeLoop(startVelocity, distance)
TimeS = zeros(size(startVelocity));
for ii = 1 : numel(startVelocity) % loop could be avoided if fallTime() is vectorised
TimeS(ii) = fallTime(startVelocity(ii), distance(ii));
end
end

3 件のコメント

Alexandra Bukowska
Alexandra Bukowska 2020 年 10 月 9 日
thank you
madhan ravi
madhan ravi 2020 年 10 月 9 日
Alexandra:
sorry, i figured it out, just need to define times with the counter too.
function times = timeLoop5(startVelocity, distance)
for i = (1:length(startVelocity))
times(i) = fallTime(startVelocity(i), distance(i));
end
end
madhan ravi
madhan ravi 2020 年 10 月 9 日
編集済み: madhan ravi 2020 年 10 月 9 日
As suggested in my answer don't use a variable named times , it'll shadow the inbuilt function times() .
Always preallocate the variable before the loop.
Never use i as an iterator because MATLAB also interprets it as an imaginary unit.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2020 年 10 月 9 日

編集済み:

2020 年 10 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by