Newbie plot
13 次查看(过去 30 天)
显示 更早的评论
Our teacher has assigned us a project to plot a function through a diode. In order words, the plot should only include positive numbers. I am not sure why my code isn't working. I'm pretty new to Matlab. Thanks.
%Plotting numbers greater than 0 for given expression
clc
in = .1
t = [0:in:10];
size(t);
max(size(t))
VL = 3.*exp(-t/3).*sin(pi*t)
while(i < max(size(t)))
if(VL < 0)
VL(i) = 0;
end
i = i+1;
end
plot(t,VL)
0 个评论
回答(3 个)
Image Analyst
2011-11-26
Since a diode doesn't let current go in the reverse direction I guess you want to clip your signal to zero when it goes negative. To do that you'd do this:
VL(VL<0) = 0;
Put it right before your call to plot(). VL<0 gives you a logical array where it's 1 (true) where the values are negative. Then it's being used as a logical index to set only those indices to zero and letting the others (where VL >= 0) remain unchanged.
3 个评论
Daniel Shub
2011-11-26
I saw it (and have now voted for it). I just wanted to provide a little more walking through. This extra hand holding would have been inappropriate when you wrote your answer (since Diego hadn't really shown what he had tried).
Image Analyst
2011-11-26
Thanks. Yeah I had to guess at what he meant since when I replied he hadn't posted any code yet.
Diego Aguilera
2011-11-26
1 个评论
Image Analyst
2011-11-26
Instead of staying up late working on it, you should have just looked for a response to your question here. If you had followed my advice I would have saved you, and Daniel, a lot of time.
Daniel Shub
2011-11-26
The neat thing about MATALB is you can often replace loops and treat signals as a vector. What your loop is doing is finding all the values of VL that are less than 0. You can write this as:
inegative = VL < 0;
This makes inegative an array the same size as VL with values of 1 when VL is negative and 0 otherwise. You can then set all the values of VL in one go ...
clippedVL = VL;
clippedVL(inegative) = 0;
Putting it all together you can write ...
t = 0:0.1:10;
VL = 3.*exp(-t/3).*sin(pi*t)
VL(VL < 0) = 0;
plot(t, VL);
This should give the same answer as your code above. The differences in speed will be small. Some people would say your answer is easier to understand, others would say mine. The real benefit of my answer is it moves you down the road to thinking about vectors. This will allow you to really benefit from MATLAB.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!