How can I make a piecewise function?
5 views (last 30 days)
Show older comments
I want to make a piece wise function that between (and including) n = 10 and 50, the function x(n) = cos(npi/20) can be evaluated, but before or after those n points the function is 0.
Then I want to make a function that has x shifted and evaluate the new output. For example, my new function is y1 = x(n+1) and shift all the values from my original x(n) to the right 1. Some of my functions will be shifted to the left too so I need to be able to shift it in both directions.
If there is a better way to do this without a piecewise please let me know.
1 Comment
Image Analyst
on 11 Sep 2018
Just to clarify, are x and y1 your vertical/y/dependent variable, and n is your horizontal/x/independent variable? What are you actually varying along your x axis (is it n?), and what is the name of the signal being plotted along the y axis (is it x?, which I think would be a bad name)?
Accepted Answer
Star Strider
on 11 Sep 2018
Edited: Star Strider
on 11 Sep 2018
Try this:
pcwsfcn = @(n,s) cos(n*pi/20 + s*pi/20) .* (((s+n) >= 10) & ((s+n) <= 50));
t = linspace(0, 60, 250);
figure
plot(t, pcwsfcn(t,0), '-b')
hold on
plot(t, pcwsfcn(t,+1), '--r')
plot(t, pcwsfcn(t,-1), '--g')
hold off
grid
Here, ‘s’ is the ‘shift’ parameter.
It uses ‘logical indexing’ to define the different regions.
EDIT — Updated code.
4 Comments
Star Strider
on 12 Sep 2018
As always, my pleasure!
Getting the shift to work correctly was an interesting challenge!
More Answers (0)
See Also
Categories
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!