How can i plot with if statement ?

1 回表示 (過去 30 日間)
maryam ahmaf
maryam ahmaf 2020 年 1 月 16 日
コメント済み: Guillaume 2020 年 1 月 16 日
>> x=[10 20 30 40 50 ] ;
>> if x==10
y=((10*10^6)*.1523)./ x ;
end
if x==20
y=((10*10^6)*.601)./ x ;
end
if x==30
y=((10*10^6)*1.914)./ x ;
end
if x==20
y=((10*10^6)*.601)./ x ;
end
if x==30
y=((10*10^6)*1.914)./ x ;
end
if x==40
y=((10*10^6)*2.73)./ x ;
end
if x==50
y=((10*10^6)*5.5547)./ x ;
end

回答 (1 件)

Star Strider
Star Strider 2020 年 1 月 16 日
Try this:
x=[10 20 30 40 50 ] ;
for k = 1:numel(x)
if x(k)==10
y(k)=((10*10^6)*.1523)./ x(k) ;
end
if x(k)==20
y(k)=((10*10^6)*.601)./ x(k) ;
end
if x(k)==30
y(k)=((10*10^6)*1.914)./ x(k) ;
end
if x(k)==20
y(k)=((10*10^6)*.601)./ x(k) ;
end
if x(k)==30
y(k)=((10*10^6)*1.914)./ x(k) ;
end
if x(k)==40
y(k)=((10*10^6)*2.73)./ x(k) ;
end
if x(k)==50
y(k)=((10*10^6)*5.5547)./ x(k) ;
end
end
figure
plot(x, y)
grid
It is necessary to index into both ‘x’ and ‘y’ to do what you want.
  1 件のコメント
Guillaume
Guillaume 2020 年 1 月 16 日
Note (to the OP) that 10*10^6 is better written as 10e6.
A much better design of the above would be:
LUT = [10, 0.1523; ...Look Up Table for x and corresponding coefficiet
20, 0.601;
30, 1.914;
40, 2.73;
50, 5.5547];
x = [10 20 30 40 50];
for k = 1:numel(x)
[found, whichrow] = ismember(x(k), LUT(:, 1));
if found
y(k) = 10e6 * LUT(whichrow, 2) / x(k);
else
error('don''t know how to calculate y(k)');
end
end
figure;
plot(x, y);
grid;
So now if you want to add/remove x values and coefficients you only have one line of a matrix to edit instead of having to copy-paste/delete several lines of codes. It's also a lot clearer what the coefficient are and it avoids having twice the same tests (e.,g. the 20 and 30 test that was repeated originally).

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeInteractive Control and Callbacks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by