Adding zero points on a plot of a damped sine wave - quick question

Greetings all,
This will probably be a quick one for you experts, but I have a damped sine wave of:
y1=2*sin(w*t).*exp(-lambda*t);
The user inputs w and lambda, and I have t=0:.001:1;
Now, since the sine wave crosses zero, I would like to add a circle or X where that crossing is just to highlight it. I played around with for and if statements, but not getting it, even though it's kinda trivial.
Any assistance?
Thanks!
-J

 Réponse acceptée

Jesse - you could compare each element to its neighbour and see if there is a switch in sign i.e. from positive to negative or negative to positive. The easiest way to do this, without a for loop, is to use arrayfun and just check to see if each neighbour is different. Something like
idcs = arrayfun(@(k)sign(y1(k))~=sign(y1(k+1)),1:length(y1)-1);
We use sign to check the sign of the number, and if the sign between two neighbouring elements is different then
sign(y1(k))~=sign(y1(k+1)
is true (or 1). Note how we use the anonymous function
@(k)sign(y1(k))~=sign(y1(k+1))
to take as an input k which will be an index into y1. The resulting logical array, idcs, will have ones where there is a difference in sign which is the zero crossing. Use find to find those indices as
find(idcs==1)
which you can then use to draw your X or circle at the zero crossing. Try the above and see what happens!

4 commentaires

Geoff,
Thanks for the response and apologies on the delay on my end. The answer you provided makes sense, but quick question here. When I tried:
plot(idcs, -t, 'or');
It threw back an error since the vectors are not the same length. True, but I was trying to put it all on the same plot with hold on, etc.
Since I'm new to "find", is there a plotfind command of some sort?
Thanks again!
Jesse - idcs would have one less element than t, so you wouldn't be able to plot the two together. I think that I gave a poor name to this variable and should be something more like
zeroCrossings = arrayfun(@(k)sign(y1(k))~=sign(y1(k+1)),1:length(y1)-1);
which is a vector of zeros (not a zero crossing) and ones (is a zero crossing). We would then need the indices of this vector that correspond to ones (the zero crossings) so
zeroCrossingIdcs = find(zeroCrossings==1);
Now we use this array of indices with y1 and t as
plot(y1(zeroCrossingIdcs), t(zeroCrossingIdcs), 'or');
(I removed the - from the t as I wasn't sure if this was a typo or intentional).
Try with the above and see if that gives a better result.
Yes that's it. Thanks Geoff!
Glad it worked out, Jesse!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by