Tanaka
Tanaka

Reputation: 53

Create and plot a piecewise function in Octave

So I want to plot this function

enter image description here

for -1

First I created the piecewise function

function x = pieceWise(t)
  if t >= 0 & t <3
    x = exp(-t);
  else
    x = 0;
endif

then called and plot it here

x = linspace(-1,5,1000);
y = pieceWise(x);
plot(x,y)

but the output is always 0

enter image description here

any hint would be very helpful. Thank you

Upvotes: 4

Views: 5975

Answers (1)

Andy
Andy

Reputation: 8091

You should vectorize you code:

1;
function x = pieceWise(t)
  x = zeros (size (t));
  ind = t >= 0 & t < 3;
  x(ind) = exp(-t(ind));
endfunction

x = linspace (-1, 5, 1000);
y = pieceWise (x);
plot (x, y)
grid on
print out.p

gives

result

Upvotes: 5

Related Questions