how to create a piecewise function using nested for/if-else loops
10 views (last 30 days)
Show older comments
Charles Moody
on 28 Jan 2018
Answered: Walter Roberson
on 28 Jan 2018
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 Comments
Accepted Answer
Walter Roberson
on 28 Jan 2018
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 Comments
More Answers (0)
See Also
Categories
Find more on Waveform Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!