how to create a piecewise function using nested for/if-else loops
조회 수: 8 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Waveform Generation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!