Help with for loop and if else statement

1 次查看(过去 30 天)
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