フィルターのクリア

How to generate a vector with the required values

169 ビュー (過去 30 日間)
Luca Cerone
Luca Cerone 2011 年 2 月 15 日
回答済み: Aneeza Aneeza 2021 年 3 月 1 日
Dear all, I just noticed that if I create a vector like x=[.1:.1:.9] the result apparently is the same as creating it manually as x=[.1 .2 .3 .4 .5 .6 .7 .8 .9]; but it is not like that!
For example
>> x=[.1:.1:.9]
x =
0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000
>> x(3)==.3
ans =
0
how can you explain that? And how can I be sure to create vectors with the required values???
FIY I'm using Matlab 2009b on a Unix environment. Cheers, -Luca
  1 件のコメント
Jan
Jan 2011 年 2 月 15 日
Should we vote this question, because it is asked very frequently? Or should we not vote it, because the best answer would be not to ask the question at all? (sorry for this illogical formulation)

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

採用された回答

Davide Ferraro
Davide Ferraro 2011 年 2 月 15 日
The syntax:
x=[.1:.1:.9]
is creating a vector incrementally and due to Floating Point arithmetic approximation the obtained value may be different from the exact value from the vector definition.
Page, Troubleshooting Common Floating-Point Arithmetic Problems perfectly explains this with some possible approaches you may consider, especially if you are planning to do some "exact" comparison with ==.

その他の回答 (3 件)

Jan
Jan 2011 年 2 月 15 日

Bruno Luong
Bruno Luong 2011 年 2 月 15 日
As Davide wrote, colon() operator will build the array by increment of the step (actually half incremental from both ends), and numerical errors will accumulate.
A more accurate way is using linspace(), which is computed by integer multiplication of the step.
a = linspace(0,1,11)
a == [0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1]
For what you want, probably the only way to get the exact value as command line is
a = eval('[0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1]')
  3 件のコメント
Bruno Luong
Bruno Luong 2011 年 2 月 15 日
Right Jos, I should write
eval(['[ ' sprintf('0.%d ',0:10) ']'])
Jan
Jan 2011 年 2 月 15 日
I assume the suggested EVAL method will increase the OP's misunderstanding of using floating point numbers in Matlab.

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


Aneeza Aneeza
Aneeza Aneeza 2021 年 3 月 1 日
Create a table of conversions from m/h to ft/s. Start the mi/h column at 0 and end it at
100 mi/hr. Print 15 values in your table. (Note: 22 ft/s = 15 m/h)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by