Search code examples
matlabplotpiecewise

How do I perform statements on the dependent variable of a graph in MATLAB?


I would like to know how to grab a specific number from an interval to test it and later be able to built a different functions under one graph. For example (in this case the 'x' variable),

 x 0:.5:5;

 Ids=ones(x);
 figure;hold on;

 for n = 1:5
     if(x < 3.0) %problem here
         Ids(n) = plot(x,x.^x);
     else 
         if (x > 4.0)  %and here
            Ids(n) = plot(x,-x.^x);
         end
     end
 end

EDIT

What I really want to do in MATLAB is to be able to do the following piecewise function:

y(x) = {  0                   (t - 5) < 0
       { (t - 5)*(t - x)      x < (t - 5)
       { (t + x^2)            x >= (t - 5)

I don't seem to understand how to graph this function since x = 0:.5:10 and t = 0:.1:10. I know how to do this without the t, but I get lost when the t is included and has different intervals compared to the x.


Solution

  • It's a little unclear from your code what you are trying to do, but it appears that you want to create and plot a function f(x) that has the following form:

    f(x) = [ x     for 3 <= x <= 4
           [ x^x   for x < 3
           [ -x^x  for x > 4
    

    If this is what you want to do, you can do the following using logical indexing:

    x = 0:0.5:5;  %# 11 points spaced from 0 to 5 in steps of 0.5
    y = x;        %# Initialize y
    index = x < 3;                   %# Get a logical index of points less than 3
    y(index) = x(index).^x(index);   %# Change the indexed points
    index = x > 4;                   %# Get a logical index of points greater then 4
    y(index) = -x(index).^x(index);  %# Change the indexed points
    plot(x,y);                       %# Plot y versus x