A graph in matlab, needs some guidance

2 visualizaciones (últimos 30 días)
googo
googo el 26 de Mzo. de 2013
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!

Respuestas (3)

Mike Garrity
Mike Garrity el 26 de Mzo. de 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.

Wayne King
Wayne King el 26 de Mzo. de 2013
Editada: Wayne King el 26 de Mzo. de 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;

googo
googo el 26 de Mzo. de 2013
thank's for the comments! but isn't there any simpler code? it's one of my first exercises in matlab and I don't think we are alowed using those functions... thank's any way...
  1 comentario
Image Analyst
Image Analyst el 26 de Mzo. de 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?

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Community Treasure Hunt

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

Start Hunting!

Translated by