Different Output using For Loop vs Elementwise operation
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Paul
2025-8-12
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
