Different Output using For Loop vs Elementwise operation

5 vues (au cours des 30 derniers jours)
Sai Gudlur
Sai Gudlur le 12 Août 2025
Commenté : Sai Gudlur le 13 Août 2025
Hello,
I have attached the code here. I see the results when compared using for loop and element wise operation are different. it is just not that the results are non-terminating or anything sometimes 2 spots past the decimal the results are differnt. Could someone tell me what I am doing wrong?
Thanks
Sai
x = linspace(0,pi,100);
y = cos(x);
z = size(x);
[row,col] = size(x);
for i = 1:col
z(i) = 1-x(i)^2/2 + x(i)^4/24;
end
z1 = 1-x.^2+x.^4/24;
plot(x,z,x,z1);
Difference = z-z1 % To know the difference if the plot above isn't clear

Réponse acceptée

Paul
Paul le 12 Août 2025
x = linspace(0,pi,100);
y = cos(x);
This probably isn't what you want. Perhaps you mean z = zeros(size(x)) or something similar.
z = size(x);
[row,col] = size(x);
for i = 1:col
z(i) = 1-x(i)^2/2 + x(i)^4/24;
end
Original code missing a divide by 2 on the second term in z1
%z1 = 1-x.^2+x.^4/24;
z1 = 1-x.^2/2+x.^4/24;
plot(x,z,x,z1);
Difference = z-z1 % To know the difference if the plot above isn't clear
Difference = 1×100
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  1 commentaire
Sai Gudlur
Sai Gudlur le 13 Août 2025
Thanks a ton. Yes I missed 2 & zeros(size(x))

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2025a

Community Treasure Hunt

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

Start Hunting!

Translated by