0

I am trying to plot ONE graph in MATLAB that has two functions that take different domains.

f1(t) = 50*t              % 0<=t<15
f2(t) = 160/3)*t - 180    % 15<=t<=60

I tried using below

t1 = 0:15;
y = f1(t1)
plot(t1,y)
hold on

t2 = 15:60 ;
y = f2(t2)
plot(t2,y)
hold off

then I get TWO graphs that do not form a continuous line. the graph from the above code

I need the red graph starting at (15,750) I can cheat and move the starting point for the second graph to be (15,750) but is there a way I can graph these as one function?

3 Answers 3

0

One option is to define a single function where each term is multiplied by the condition for t, effectively zeroing it out when not applicable

f = @(t) (50*t).*(t<15) + ((160/3)*t - 180).*(t>=15);

t = 0:60;
plot( t, f(t) );

If your functions are complex then this could become slightly hard to read, but it's compact.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help! It's my first question on StackOverflow, I didn't expect to get the input this soon. Your code looks very nice too ;-;
This did the job! Thank you so much!
0

Two methods. Using loop and without loop.

f1 = @(t) 50*t              % 0<=t<15
f2 = @(t) 160/3*t - 180    % 15<=t<=60

t = 0:60 ; 
f = [f1(t(t<15)) f2(t(t>=15))] ;
plot(t,f)

With loop

f1 = @(t) 50*t              % 0<=t<15
f2 = @(t) 160/3*t - 180    % 15<=t<=60
f = zeros(size(t)) ;
for i = 1:length(t)
    if t(i) < 15
        f(i) = f1(t(i)) ;
    else
        f(i) = f2(t(i)) ;
    end
end
plot(t,f)

1 Comment

Thank you so much! It looks a lot nicer in your first solution compared to mine :D
0

I realized that I needed to make the domain uniform.

%setting domain t (0 <= t <15 and 15 <= t)
t = [0:30]; %suppose match time is 30 seconds

t1 = t(1:16);
t1(numel(t)) = 0; %f1 takes t1 as domain (0 <= t < 15):array 17-31 is filled with 0

t2 = t(16:31);
t2 = [zeros(1, max(0, 15)), t2];  %f2takes t2 as domain (15 <= t):array 1-16 is filled with 0
t2(1:16) = 15;   %array 0-16 is filled with 15, to cancel (t-15) in the function 

f= f1(t1) + f2(t2); %Moira's dmg from two domains are added to form one data set

plot(t,f, 'm--') %plotting f 

here is my end result using the method above

I still need to get my domains correct I think. The graph doesn't look as it is supposed to hahaha

2 Comments

It is conventional to edit your original question if the scope changes or it needs clarifying, otherwise existing answers can become obsolete
@Wolfie I didn't mean to make things complicated, I'm not quite familiar with how StackOverflow works. Thank you for letting me know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.