Different Output using For Loop vs Elementwise operation
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!