MATLAB: How to create a piecewise function using nested for/if-else loops

piecewise function

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

Best Answer

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
Related Question