for loop to while loop
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Faisal Al-Wazir
le 9 Jan 2023
Réponse apportée : Eric Delgado
le 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 commentaires
Réponse acceptée
Eric Delgado
le 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 commentaires
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!