for loop to while loop
2 views (last 30 days)
Show older comments
Faisal Al-Wazir
on 9 Jan 2023
Answered: Eric Delgado
on 9 Jan 2023
im trying to convert the code to while loop but im failing to see the mistake
%% while loop
clc
clear
x=16
X=[0,10,15,20,22.5,30]
Y=[0,227.04,362.78,517.35,602.97,901.67]
D=length(X)
j=1
j1=1
i=1
while j<D
z(i)=1
while j1<D
if i~=j
z(i)=z(i)*(x-X(j))/(X(i)-X(j))
end
j1=j1+1
end
z(i)=z(i)*Y(i)
j=j+1
i=i+1
end
sum(z)
%% for loop
clc
clear
x=16
X=[0,10,15,20,22.5,30]
Y=[0,227.04,362.78,517.35,602.97,901.67]
D=length(X)
for i=1:D
z(i)=1
for j=1:D
if i~=j
z(i)=z(i)*(x-X(j))/(X(i)-X(j))
end
end
z(i)=z(i)*Y(i)
end
sum(z)
0 Comments
Accepted Answer
Eric Delgado
on 9 Jan 2023
Try this...
x=16;
X=[0,10,15,20,22.5,30];
Y=[0,227.04,362.78,517.35,602.97,901.67];
D=length(X);
% WHILE LOOPS
i=1;
while i <= D
z1(i)=1;
j = 1;
while j <= D
if i~=j
z1(i) = z1(i) * (x-X(j))/(X(i)-X(j));
end
j = j+1;
end
z1(i) = z1(i)*Y(i);
i=i+1;
end
% FOR LOOPS
for i = 1:D
z2(i) = 1;
for j = 1:D
if i ~= j
z2(i) = z2(i) * (x-X(j))/(X(i)-X(j));
end
end
z2(i) = z2(i)*Y(i);
end
isequal(z1, z2)
0 Comments
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!