I have tried to make a loop where it displays all the answers in a matrix but it doesn't give me the 21x3 matrix. Am i using wrong commands or am i missing something.

1 回表示 (過去 30 日間)
t=0;
for v=[t,sin(t),cos(t)]
if t<21
disp(v)
t=t+1;
end
end
  2 件のコメント
merlin kelly
merlin kelly 2018 年 11 月 14 日
I was going through matlab onramp and i am at the loop section so i tried to do the loop on that one. I wasn't getting the answer so i was trying to get a display first but now im trying to plot a graph of it

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

採用された回答

Luna
Luna 2018 年 11 月 14 日
Hi Merlin,
try this code below:
v = [];
for t = 0:1:20
v(t+1,:) = [t,sin(t),cos(t)] ;
end
  2 件のコメント
merlin kelly
merlin kelly 2018 年 11 月 14 日
Thank you this was very helpful, what happens when v = [ ];, shouldn't i write down v=[t,sin(t),cos(t)] or will that not work
Luna
Luna 2018 年 11 月 15 日
actually I prefer to define v = nan(21,3). Pre-allocation of the size increases the performance, and speed up the for loop.
defining empty ( v = [] ) is something about usage.
For example: if you use your for loop in if-else block, defining empty in the beginning helps you understand whether it goes to if or else block, etc.
You can easily check if isempty(v) that your matrix filled with values or remained empty at end of the process.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by