Displaying non existant array elements

3 次查看(过去 30 天)
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 个评论
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 CenterFile Exchange 中查找有关 Resizing 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