for loop to while loop
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Faisal Al-Wazir
am 9 Jan. 2023
Beantwortet: Eric Delgado
am 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 Kommentare
Akzeptierte Antwort
Eric Delgado
am 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!