Thread: plotting a graph in matlab

1. plotting a graph in matlab

Hi i am having trouble with matlab figuring out a code to plot a graph with conditions

x in (0,10)

i want a code for
f(x - 2) = 2 for 0 <x-2<2
f(x - 2) = 1 for 2 <x-2<10

so i want to plot this for varying x
can anyone help me with the code

thanks

2. I think that would use a "for" loop.

It might help to define $t=x-2$.

Can I ask what the function is?

3. Originally Posted by Showcase_22
I think that would use a "for" loop.

It might help to define $t=x-2$.

Can I ask what the function is?
basically my question is solve u_t + 2u_t=0 for x in(0,10) using matlab, with initial and boundary conditions..i have done the hard part of creating a code to solve this.

But i need to compare these results for a general solution they have given.

i.e u(x,t) = g(t-x/2) for x<2t
and u(x,t) = f(x-2t) for x>2t

with u(o,t)=g(t)= 2 + 0.5*sin(2*pi*t)
and u(x,0) = f(x) =2 for 0<x<2
and u(x,0) = f(x) =1 for 2<x<10

so i am trying to draw a sketch in matlab for different time slices of t.
for the query i wrote earlier i used t=1

so i got
u(x,1) = g(1-x/2) for x<2
and u(x,1) = f(x-2) for x>2

where g(1-x/2) = 2+ 0.25*sin(2*pi*(1-x/2)
and f(x-2) = 2 for 0<x-2<2
and f(x-2) = 1 for 2<x-2<10

and so i want sketch u(x,1) on matlab for varying x
..
a loop statement i used in my original code work was
N=4;
xmin=0;
xmax=10;

x=linspace(xmin,xmax,N+1);

for n=1:N+1;
if x(n) > 0 && x(n) < 2;
u_init_test(n)=2;
elseif x(n) > 2 && x(n) < 10;
u_init_test(n)=1;
else u_init_test(n)=0;
end
end
u_init=u_init_test;

i dont know if this helps but could it be adapted to help me solve my problem

thanks

4. Originally Posted by dopi
Hi i am having trouble with matlab figuring out a code to plot a graph with conditions

x in (0,10)

i want a code for
f(x - 2) = 2 for 0 <x-2<2
f(x - 2) = 1 for 2 <x-2<10

so i want to plot this for varying x
can anyone help me with the code

thanks
Code:
x=[0:0.1:10];
y=x-2;

f=2*ones(size(y))+(y>=2)*(-2+1);

plot(x,f);
will do it.

CB