Piecewise Function in MATLAB

  • Thread starter STEMucator
  • Start date
  • #1
STEMucator
Homework Helper
2,075
140

Homework Statement



Hey there. I'm trying to plot a piecewise function in MATLAB and I'm having some decent success, but there's some things I'm wondering.

Here's the function: http://gyazo.com/d3493a0c13096878acf5a501af8a7f66


Homework Equations





The Attempt at a Solution



My strategy was to create an empty array to hold all the y values since plotting the x values is easy enough. I came up with this short snippet of code:

Code:
function plotFunction()
y = []; %Empty array to hold the y values

for i=-40:0.05:30
    if i <= 0
        y(end+1) = 38/11 + sin(i^2);
    elseif i <= 9
        y(end+1) = 38/(11-i);
    else
        y(end+1) = 1.5*sqrt(4*i) + 10;
    end
end

plot(-40:0.05:30, y);
title('Piecewise Function Plot');
xlabel('x-values');
ylabel('y-values');

end
This code yields the following plot, which is really close, but there's something wrong:

http://gyazo.com/1ef70c9ccf6c44f81c14d9915c9edf86

What's with the funky activity near ##x = -30##? Why does it get all clumped up around there?

I tried tinkering with the increment of 0.05, but shrinking it clumps the graph together even more.
 

Answers and Replies

  • #2
818
67
What's with the funky activity near ##x = -30##? Why does it get all clumped up around there?
It's an artifact of sampling the waveform and plot doing linear interpolation. Try, for instance, to use an increment of 0.001 instead.
 

Related Threads on Piecewise Function in MATLAB

Replies
1
Views
4K
Replies
1
Views
11K
  • Last Post
Replies
5
Views
815
Replies
4
Views
13K
Replies
5
Views
7K
Replies
1
Views
1K
Replies
0
Views
5K
  • Last Post
Replies
3
Views
3K
Replies
12
Views
1K
  • Last Post
Replies
5
Views
4K
Top