0

I'm trying to plot a simple piecewise defined function in MATLAB R2016a. While t is negative, this code should plot v = 0 and when t is positive (or zero), the code should plot v = 10*exp(-5000*t). Here's the code:

t = -0.0014:1e-5:0.0014;
v = zeros(1, length(t));
for i = 1:length(t)
    if t(i) < 0
        v(i) = 0;
    elseif t(i) >= 0
        v(i) = 10*exp(-5000*t);
    end
end
plot(t, v)

This m-file looks right to me, but I keep getting the error

In an assignment  A(:) = B, the number of elements in A and B must be the same.

Error in PiecewiseFunction (line 10)
        v(i) = 10*exp(-5000*t);

I suspect it's something simple, but I just don't see it!

Andy
  • 789
  • 8
  • 19
  • 5
    `v(i) = 10*exp(-5000*t(i));` – TroyHaskin Jun 17 '16 at 02:34
  • 3
    Given the Matlab error message was very useful (as they usually are), you know the problem is because "the number of elements in A and B must be the same", so that means that the number of elements in `v(i)` and `10*exp(-5000*t)` must be different. To further debug this, you could have done `size(v(i))` and `size(10*exp(-5000*t))` on the 2 lines before the error. This would have shown what the problem was, then you just need to work out how to fix it. Matlab error messages are very useful, read them and think about what they are saying! – David Jun 17 '16 at 02:39
  • Excellent solution and comments! – Andy Jun 17 '16 at 22:22

1 Answers1

2

The comments on the question answer it, but you can make this code much simpler if you vectorize it:

v = 10*exp(-5000*t).*(t >= 0);
CKT
  • 781
  • 5
  • 6