how to create a piecewise function using nested for/if-else loops

10 ビュー (過去 30 日間)
Charles Moody
Charles Moody 2018 年 1 月 28 日
回答済み: Walter Roberson 2018 年 1 月 28 日
I have no idea how to use MATLAB:
I'm trying to generate a two pulse waveform like so:
x = 0:.02:2;
g = zeros(length(x));
for k = 0:length(x)
if 0<= x(k) < 1/3
g(k) = 0;
elseif 1/3 <= x(k) < 1/2
g(k) = 1;
elseif 1/2 <= x(k) < 4/3
g(k) = 0;
elseif 4/3 <= x(k) <5/3
g(k) = -1;
else
g(k) = 0;
end
end
plot(x,g, 'r')
but every time I try and run the program it gives me an error code saying "Subscript indices must either be real positive integers or logicals."
I don't know wht to do

採用された回答

Walter Roberson
Walter Roberson 2018 年 1 月 28 日
if 0<= x(k) < 1/3
in MATLAB means the same as
if all((0<= x(k)) < 1/3)
the 0<=x(k) part returns either false (0) or true (1) . The < 1/3 part then compares that 0 or 1 to 1/3 .
There are no MATLAB operators to compare ranges (I am not sure I have ever see a language that has such an operation, but perhaps there is.)
You need to code each part separately:
if 0 <= x(k) && x(k) < 1/3

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWaveform Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by