Displaying non existant array elements

조회 수: 2 (최근 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 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