I don't get it... Help plotting this on MATLAB?

1 view (last 30 days)
I can't seem to figure out how to solve this question. I've tried looking at an example and doing it but this has more variables and I'm just not getting the result I'm supposed to.
I've heard that using a for loop would work when incrementing and calculating each values, but it's just too confusing.
Files are attached... Any help would be very much appreciated.
Please and thank you!
Annalise on 21 Mar 2015
I looked through, and made a few adjustments to my code, however, the plotting part looks a lot more complicated than it has to be...

Sign in to comment.

Accepted Answer

Giorgos Papakonstantinou
Giorgos Papakonstantinou on 21 Mar 2015
Edited: Giorgos Papakonstantinou on 21 Mar 2015
Annalise I will try to demonstrate how you may plot a piecewise function. In a similar manner you may plot yours.
Lets assume you have a vector:
x = -10:1:10;
And you have a piecewise function such as f(x) = |x|. This function is defined as:
  • f = |x|, x<0
  • f = 0, x=0
  • f = |x|, x>0
To define the three different intervals of x in Matlab you should this:
s1 = x<0;
s2 = x==0;
s3 = x>0;
To define the values of f in these intervals you should do this:
f(s1) = -x(s1);
f(s2) = 0;
f(s3) = x(s3);
To plot f with stem:
stem(x(s1), y(s1), 'r')
hold on
stem(x(s2), y(s2), 'g')
stem(x(s3), y(s3))
As you see a for loop is not necessary for a piecewise function which is defined on 3 intervals.
Annalise on 21 Mar 2015
Edited: Annalise on 21 Mar 2015
Thank you so much for all your help ^^
For the moment, I deleted the zero value one (f1) leaving the other two, so there are no logical values. It doesn't make a difference to the result so I'm happy with that, since submission is in a few hours and my is too frazzled up to think about this clearly.
I'll read through everything again, tomorrow, and try to fix the code up to the way it should be. Once again, thank you so very very much. It's much appreciated.

Sign in to comment.

More Answers (0)


Find more on Loops and Conditional Statements in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!