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!