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!