Different Output using For Loop vs Elementwise operation

5 Ansichten (letzte 30 Tage)
Sai Gudlur
Sai Gudlur am 12 Aug. 2025
Kommentiert: Sai Gudlur am 13 Aug. 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

Akzeptierte Antwort

Paul
Paul am 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
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>

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2025a

Community Treasure Hunt

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

Start Hunting!

Translated by