Different Output using For Loop vs Elementwise operation
5 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Paul
on 12 Aug 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
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!