Displaying non existant array elements

3 visualizaciones (últimos 30 días)
Ali Kiral
Ali Kiral el 8 de Mzo. de 2025
Editada: dpb el 8 de Mzo. de 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 comentario
Stephen23
Stephen23 el 8 de Mzo. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

dpb
dpb el 8 de Mzo. de 2025
Movida: dpb el 8 de Mzo. de 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 comentarios
Ali Kiral
Ali Kiral el 8 de Mzo. de 2025
Great! Thanks a billion
dpb
dpb el 8 de Mzo. de 2025
Editada: dpb el 8 de Mzo. de 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..

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by