How can I make a piecewise function?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Anonymous
il 11 Set 2018
Commentato: Star Strider
il 12 Set 2018
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 Commento
Image Analyst
il 11 Set 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)?
Risposta accettata
Star Strider
il 11 Set 2018
Modificato: Star Strider
il 11 Set 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 Commenti
Star Strider
il 12 Set 2018
As always, my pleasure!
Getting the shift to work correctly was an interesting challenge!
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!