How can I make a piecewise function?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2018-9-11
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)?
采纳的回答
Star Strider
2018-9-11
编辑:Star Strider
2018-9-11
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 个评论
Star Strider
2018-9-12
As always, my pleasure!
Getting the shift to work correctly was an interesting challenge!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!