Displaying non existant array elements

2 Ansichten (letzte 30 Tage)
Ali Kiral
Ali Kiral am 8 Mär. 2025
Bearbeitet: dpb am 8 Mär. 2025
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 Kommentar
Stephen23
Stephen23 am 8 Mär. 2025

“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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

dpb
dpb am 8 Mär. 2025
Verschoben: dpb am 8 Mär. 2025
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 Kommentare
Ali Kiral
Ali Kiral am 8 Mär. 2025
Great! Thanks a billion
dpb
dpb am 8 Mär. 2025
Bearbeitet: dpb am 8 Mär. 2025
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..

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by