Plot, if and elseif statement

10 visualizaciones (últimos 30 días)
John
John el 6 de Abr. de 2011
Can some1 please help me with this.
Plot function f(x) over x=0:pi/10:2*pi
f(x)=sin(x) if (x<=pi)
f(x)=cos(x)+1 if (x>pi)
This is what I started so far and don't know what to do next.
x=0:pi/10:2*pi;
if x<=pi
xx=sin(x)
elseif x>pi
yy=cos(x)+1
end

Respuestas (1)

Matt Fig
Matt Fig el 6 de Abr. de 2011
IF statements do not pick out elements of an array as you are thinking they do. Use logical indexing.
x = 0:pi/10:2*pi;
y = zeros(size(x));
idx = x<=pi;
y(idx) = sin(x(idx));
y(~idx) = cos(x(~idx))+1;
plot(x,y)
If you really want to use an IF statement, you will need to look element-by-element.
y = zeros(size(x));
for ii = 1:length(x)
if x(ii)<=pi
y(ii) = sin(x(ii));
else
% ... fill it in.
end
end
  1 comentario
Matt Fig
Matt Fig el 6 de Abr. de 2011
Should this be a FAQ? It seems like the
if x<3,...
construction for vectors is coming up all the time recently....

Iniciar sesión para comentar.

Categorías

Más información sobre Language Fundamentals en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by