Plotting a Piecewise function

7 views (last 30 days)
Lauren
Lauren on 11 Oct 2013
Answered: sixwwwwww on 14 Oct 2013
I currently have this as a script:
function W
t= (1:56)
while t>=1 & t<=28
Ws
t=48+3.6*t+.6363*t^2+.00963*t^3
end
while 28<t & t<=56
Wr
t=-1004+65.8*t
end
function Ws
disp('t is greater than or equal to 1 and t is less than or equal to 28')
end
function Wr
disp ('t is greater than 28 and less than or equal to 56')
end
end
function graph;W (1,56)
N=1000;
n=(56-1)/N;
x=[1:.055:56];
i=1:length(x);
F(i)=W(x(i));
end
plot(x,F)
xlabel('Time')
ylabel('Body Weight')
end
Everything seems to go through matlab okay except that I cannot get it to graph. How can I change this to get it to graph?
  1 Comment
dpb
dpb on 11 Oct 2013
Format the code so it's legible -- (put in line break and then two spaces before the first line of code...break lines as needed)

Sign in to comment.

Answers (3)

Jan
Jan on 14 Oct 2013
Edited: Jan on 14 Oct 2013
I think, this will not do what you want:
t = (1:56)
while t>=1 & t<=28
Ws
t=48+3.6*t+.6363*t^2+.00963*t^3
end
while produces the scalar dimensions of the condition by inserting an all():
while all(t>=1 & t<=28)
Now all elements of the vector t are transformed by the polynomial until any element is < 1 or > 28. Is this your intention?
Or do you want:
t = 1:56;
tt(1:28) = 48+3.6*t+.6363*t^2+.00963*t^3;
tt(29:56) = -1004+65.8*t;
?
The next problem is:
function graph;W (1,56)
What should this do? The function W does not use input arguments. The function graph is not called from anywhere.
I recommend to read the Getting Started chapters of the documentation and to use the debugger to step through the code line by line until it gets clear, what's going on.

Vivek Selvam
Vivek Selvam on 14 Oct 2013
This might be a starting place for a running code.
function graph
N=1000;
n=(56-1)/N;
x=[1:n:56];
for i=1:length(x)
F(i)=W(x(i));
end
plot(x,F)
xlabel('Time')
ylabel('Body Weight')
end
function F = W(t)
if t>=1 && t<=28
Ws
F=48+3.6*t+.6363*t^2+.00963*t^3
end
if 28<t && t<=56
Wr
F=-1004+65.8*t
end
function Ws
disp('t is greater than or equal to 1 and t is less than or equal to 28')
end
function Wr
disp ('t is greater than 28 and less than or equal to 56')
end
end

sixwwwwww
sixwwwwww on 14 Oct 2013
Dear Lauren, do you need following functionality in your code:
j = 1:56;
t = zeros(1, length(j));
for i = 1:56
if (i >= 1 && i < 29)
disp('t is greater than or equal to 1 and t is less than or equal to 28')
t(i) = 48 + 3.6 * i + .6363 * i^2 + .00963 * i^3;
else if (i > 28 && i <= 56)
disp ('t is greater than 28 and less than or equal to 56')
t(i) = -1004 + 65.8 .* i;
end
end
end
N = 1000;
x = min(j):((max(j) - min(j)) / N):56;
F = interp1(j, t, x);
plot(x, F), xlabel('Time'), ylabel('Body Weight')
If yes then tell me which functions you need to do what work so that this code can be converted to functions

Community Treasure Hunt

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

Start Hunting!