Help with for loop and if else statement

조회 수: 1 (최근 30일)
Rachna Singh
Rachna Singh 2022년 1월 13일
댓글: Rachna Singh 2022년 1월 13일
I am writing to code for the attached capture 1 image, and it is supposed to obtain the graph as shown in the capture 2 image.
I used for and if-else statement to write the code, however it is not working. If possible can anyone look into it? Thanks in advance.
y=0:1000;
for i=0:length(y)
if y(i) <= 10
Q1=1;
elseif (y(i) > 10) && (y(i)<100)
Q2=0.32*y-2.2;
else y(i) > 100
Q3 =300/sqrt(y);
end
Q=(Q1+Q2+Q3)
end
semilogx(y,Q)

답변 (3개)

Image Analyst
Image Analyst 2022년 1월 13일
편집: Image Analyst 2022년 1월 13일
You need to index L and Q:
L = linspace(0, 200, 2000);
Q = ones(1, length(L)); % Initialize to 1
for k = 2 : length(L)
if L(k) <= 10
Q(k) = 1;
elseif (L(k) > 10) && (L(k)<= 100)
Q(k)=0.32 * L(k) - 2.2;
elseif L(k) > 100
Q(k) =300/sqrt(L(k));
end
% Q=(Q1+Q2+Q3)
end
loglog(L, Q, 'LineWidth', 3);
grid on;
xlabel('L', 'FontSize', 20)
ylabel('Q', 'FontSize', 20)
Of course you don't need a loop - you can do it vectorized if you want but it's your homework so I didn't try to modify it too much.

Mathieu NOE
Mathieu NOE 2022년 1월 13일
hello
here you are .
Q andy must be indexed in the loop (Q(k) , y(k))
only one Q variable suffice for all cases - no need to create multiple Q's
also please don't use i or j for loop index as your are shadowing their native role (i = j = sqrt(-1) for complex numbers)
clc
clearvars
y=1:1000;
for k=1:length(y)
if y(k) <= 10
Q(k)=1;
elseif (y(k) > 10) && (y(k)<100)
Q(k)=0.32*y(k)-2.2;
else y(k) > 100
Q(k) =300/sqrt(y(k));
end
end
loglog(y,Q)

Rachna Singh
Rachna Singh 2022년 1월 13일
Thank you everyone :)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by