Help with for loop and if else statement

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)

Réponses (3)

Image Analyst
Image Analyst le 13 Jan 2022
Modifié(e) : Image Analyst le 13 Jan 2022
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 le 13 Jan 2022
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)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by