A graph in matlab, needs some guidance
2 views (last 30 days)
Show older comments
Hey,
First question : Suppose I have two vectors : x = [1 2 3] and y=[0.5,0.35,0.15] and I want to draw a graph using only the plot function but I'm intrested that from 1-2 y will be 0.5 ,from 2-3 y will be 0.35 and from 3+ y will be 0.15... like steps.
________
_____________
______________
How can I do it?
Second quesition: how do I combine xlim and ylim functions in the plot function?
thank's!
1 Comment
Walter Roberson
on 26 Mar 2013
please review the guide to tags and retag your question. see http://www.mathworks.co.uk/matlabcentral/answers/43073-a-guide-to-tags
Answers (3)
Mike Garrity
on 26 Mar 2013
The stair function is probably closer to what you want, but you can do it with plot if you tell it what to do in detail.
Basically, you need to add a new point for the end of each line segment, and another point "between" the line segments. That third point will get the value nan to tell the plot command to stop drawing. Here's a MATLAB-golf like solution:
x2=repmat(x,[3,1]);
y2=repmat(y,[3,1]);
x2(:,4)=numel(x);
y2(3,:)=nan;
plot(x2(3:11),y2(:))
What's going on is that the two calls to repmat give us 3 copies of the X and Y values. Now we add the value 4 onto the end of the X values to get the right side of the last line. And we stick nans into the last row of the Y values.
Finally when we plot them, we need the X and Y values to be out of phase. This makes the X change between the first two points, then the Y change between the next pair, etc.
0 Comments
Wayne King
on 26 Mar 2013
Edited: Wayne King
on 26 Mar 2013
x = 1:0.1:4-0.1;
y = [0.5 0.35 0.15];
ynew = zeros(size(x));
ynew(1:10:end) = y;
ynew = filter(ones(10,1),1,ynew);
stem(x,ynew);
set(gca,'xlim',[1 3.5]);
set(gca,'ylim',[0 0.6]);
grid on;
If you use
plot(x,ynew)
above you'll get a sloped line where your plot actually has a discontinuity, so if you don't like stem(), use
stairs(x,ynew)
set(gca,'xlim',[1 3.5]);
set(gca,'ylim',[0 0.6]);
grid on;
0 Comments
googo
on 26 Mar 2013
1 Comment
Image Analyst
on 26 Mar 2013
Stairs() is a legitimate function of MATLAB. That is the simplest way. The 3 other lines Wayne added are just to make the graph pretty. By the way, your "Answer" here should have been a comment to Wayne's answer, not an "Answer" in itself. If you can't use certain functions then please list which functions are banned, and if possible say why those certain functions are banned while other are okay. Is there any rationale to it?
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!