for loop to while loop
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Eric Delgado
2023 年 1 月 9 日
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 件のコメント
その他の回答 (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!