How to use a for loop to solve a function?

Not sure where I'm going wrong. While loop works correctly, but not sure what's happening with the for loop.
x=linspace(0,20,20);
a=0;
while(a<=20)
y=x.^6-(3.*x).^2+3.^x-(230.*x);
a=a+1;
end
for j=1:20
y2(j)=100.*3log(j)-(2.*j);
end
When plotting, the while loop plots how it should, but nothing shows up for the for loop. Any guidance welcome. Thank you!

답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 9월 13일

0 개 추천

In your code, the while loop has no use. I think you wanted to write it like this
while(a<=20)
y(a)=x(a).^6-(3.*x(a)).^2+3.^x(a)-(230.*x(a));
a=a+1;
end
The for loop seems fine except there is a typing error. Following should work fine and you can plot the output
for j=1:20
y2(j)=100.*3*log(j)-(2.*j);
end

댓글 수: 2

Jer D
Jer D 2020년 9월 13일
Sorry for the confusion. The while loop was used to solve for one function, and the for loop is for another function. I'm trying to get them to plot on one graph however, only the while loop is graphing which made me assume that my for loop isn't working. For some reason, the for loop won't graph at all.
Ameer Hamza
Ameer Hamza 2020년 9월 14일
편집: Ameer Hamza 2020년 9월 14일
They are both visible, but y2 have very small values as compared to y, so it is on lower part axes (see the orange line on x-axes
x=linspace(0,20,20);
a=1;
while(a<=20)
y(a) = x(a).^6-(3.*x(a)).^2+3.^x(a)-(230.*x(a));
a=a+1;
end
for j=1:20
y2(j) = 100.*3*log(j)-(2.*j);
end
f = figure();
hold on;
plot(y);
plot(y2);

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 9월 13일

편집:

2020년 9월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by