How do I write an m-file for a piece wise function?

The equation is:
W(t) = 48+3.64t+0.6363t^2+0.00963t^3 when 1 <= t <= 28
W(t) = -1004+65.8t when 28 < t <= 56

Answers (1)

W = nan(size(t));
idx = (1 <= t & t <= 28);
W(idx) = 48 + 3.64 * t(idx) == 0.6363 * t(idx).^2 + 0.00963*t(idx).^3;
idx = (28 < t & t <= 56);
W(idx) = -1004 + 65.8 * t(idx);
This will leave W as NaN for any t outside the range 1 <= t <= 56
Warning: 48+3.64t=0.6363t^2+0.00963t^3 is a logical comparison, not an pure arithmetic operation. Notice you have an "=" between 3.64t and 0.6363t. I coded this as == in the above. I suspect you meant "-" instead; if so then change the == to - .

5 Comments

That is actually meant to be a "+". Sorry for the typo. Does that change the equation at all?
Just change the == in my answer into a +
I'm trying to check my work by putting in a value for t, but it keeps saying t is an undefined value. How can I input a value for t to make it work?
When I try to run it, it says "Error in run (line 1) W = nan(size(t));" How can I fix this?

Sign in to comment.

Asked:

on 10 Oct 2013

Commented:

on 10 Oct 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!