Displaying non existant array elements

3 ビュー (過去 30 日間)
Ali Kiral
Ali Kiral 2025 年 3 月 8 日
編集済み: dpb 2025 年 3 月 8 日
Why am I getting repeating numbers for the array x as an output for the following piece of script?
x=1:0.5:5;
for i=1:length(x);
y(i)=x(i)^2;
end
fprintf(' x y\n')
x y
Results=[x;y];
fprintf('%10.0f %38.16f\n', Results);
1 1.0000000000000000 2 2.2500000000000000 2 4.0000000000000000 2 6.2500000000000000 3 9.0000000000000000 4 12.2500000000000000 4 16.0000000000000000 4 20.2500000000000000 5 25.0000000000000000
  1 件のコメント
Stephen23
Stephen23 2025 年 3 月 8 日

“Why am I getting repeating numbers for the array x as an output for the following piece of script?”

You are not getting the same values repeating in x. You just confused how values are displayed with the values stored in memory. Try printing the values of x with e.g. two decimal places. Then tell us what you see.

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

採用された回答

dpb
dpb 2025 年 3 月 8 日
移動済み: dpb 2025 年 3 月 8 日
x=1:0.5:5;
for i=1:length(x);
y(i)=x(i)^2;
end
fprintf(' x y\n')
x y
Results=[x;y];
fprintf('%10.2f %38.2f\n', Results);
1.00 1.00 1.50 2.25 2.00 4.00 2.50 6.25 3.00 9.00 3.50 12.25 4.00 16.00 4.50 20.25 5.00 25.00
Because the '%10.0f' required rounding the x values to display integer values...
  2 件のコメント
Ali Kiral
Ali Kiral 2025 年 3 月 8 日
Great! Thanks a billion
dpb
dpb 2025 年 3 月 8 日
編集済み: dpb 2025 年 3 月 8 日
No problem...as @Stephen23 notes directly and my response says same thing indirectly, you have to remember the difference between what the variable value and its representation may be.
BTW, you do recognize that with MATLAB array syntax you can eliminate the need for the for...end loop in the above, right?
x=1:0.5:5;
y=x.^2;
Results=[x;y];
fprintf('%10s%38s\n','x','y')
x y
fprintf('%10.2f %38.2f\n', Results);
1.00 1.00 1.50 2.25 2.00 4.00 2.50 6.25 3.00 9.00 3.50 12.25 4.00 16.00 4.50 20.25 5.00 25.00
NOTA BENE the "dot operator" on the expnentiation power, .^: to indicate element-wise operations rather than mpower, ^: which is matrix exponentiation..

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by