Piecewise function with function input?

Hello, I'm trying something really simple but I can't seem to make it work on matlab. There's these functions:
kHz,
V , and
s.
I want to plot and between 0 and 2 ms. I've tried piecewise, using functions, syms, but I just can't never seem to make it work. Suggestions?

 Accepted Answer

I hope this is not homework. If it is, you cannot ethically use this solution.
Break it up into its component functions, then use logical indexing for the threshold condition:
f = 1E+3;
vr = 0.72;
tau = 1;
vi = @(t) sin(2*pi*f*t);
vd = @(t,vr) (1-vi(t)).*(vi(t)>vr);
vo = @(t) vd(t,vr).*exp(-t/tau);
t = linspace(0, 2, 150)*1E-3;
figure
plot(t, vi(t), t, vo(t))
grid
That ran without error. Check it to be certain it matches the functions.

4 Comments

Thank you. It's not homework, I just wanted to learn how to do this sort of thing on matlab, it's very useful to know this as you can imagine! So this line of code:
vd = @(t,vr) (1-vi(t)).*(vi(t)>vr);
basically makes the function vd equal to 1-vi only when vi>vr, otherwise it will be 0, if I understood correctly? And the operator .* is there because it's multiplying arrays?
What if I wanted vd to do the following?
How would that work out?
As always, my pleasure!
... makes the function vd equal to 1-vi only when vi>vr, otherwise it will be 0, if I understood correctly? And the operator .* is there because it's multiplying arrays?
Exactly! Correct for both.
The new definition for ‘vd’ would be:
vd = @(t,vr) (vr).*(vi(t)>vr) + (vi(t)).*(vi(t)<vr);
This uses the same logic, and since the two conditions never overlap, one will always be false (0) when the other is true (1), so adding them is appropriate. I tested that to be certain it works. It does, and produces the appropriate figure when plotted.
The only improvement I would suggest is for one condition to be <= when the other is >, or the reverse, as appropriate. This willl prevent discontinuities when the conditions are equal to the test condition, since they would then be false (0) if not specifically included in the comparisons.
That made a lot of sense, thank you so much!
As always, my pleasure!

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!