I'm trying to get a vector from a loop without doing the linspace function

3 ビュー (過去 30 日間)
Kelsey Pettrone
Kelsey Pettrone 2020 年 9 月 6 日
コメント済み: Matt J 2020 年 9 月 6 日
in the command window I want it to look like this
The vector created using the for loop is:
0 1.2500 2.5000 3.7500 5.0000
here is my code
vector = zeros(1,5);
for i = 0:1.25:5;
vector = i
end
disp(vector)
this only shows the 5 but i want it to display all of them in a line

回答 (2 件)

Matt J
Matt J 2020 年 9 月 6 日
You must tell the code where in vector you want each value placed.

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 9 月 6 日
vector = zeros(1,5);
j = 1;
for i = 0:1.25:5;
vector(j) = i;
j = j+ 1;
end
disp(vector)
  3 件のコメント
Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 9 月 6 日
It works well for me.
you can use this code too:
vector = zeros(1,5);
for i = 1:5
vector(i) = 1.25*(i-1);
end
disp(vector)
Matt J
Matt J 2020 年 9 月 6 日
This would be more numerically stable. Note that solutions based on a:b:c are susceptible to floating point errors, e.g.,
>> 0:1.25+1e-14:5
ans =
0 1.2500 2.5000 3.7500

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

カテゴリ

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