define function in one line

84 visualizaciones (últimos 30 días)
fumio hakamada
fumio hakamada el 23 de Feb. de 2024
Comentada: Rik el 23 de Feb. de 2024
How can I define vector p without using function statement?
suppose
t = 0:0.1:1
p = sin(t) when t<0.6
p = 0 when t>=0.6
  2 comentarios
DGM
DGM el 23 de Feb. de 2024
Editada: DGM el 23 de Feb. de 2024
What's wrong with just
t = 0:0.1:1;
p = sin(t).*(t<0.6);
plot(t,p)
... of course, the range and resolution of t makes this plot appear a bit unclear.
fumio hakamada
fumio hakamada el 23 de Feb. de 2024
Thank you for your reply.

Iniciar sesión para comentar.

Respuesta aceptada

Rik
Rik el 23 de Feb. de 2024
I don't know if you want to avoid anonymous functions as well, but this should give you a finer plot:
% p = sin(t) when t<0.6
% p = 0 when t>=0.6
p = @(t) (t<0.6).*sin(t);
fplot(p,[0 1])
The problem here is mostly that sin(x) is very close to x for small x, which means you have a fairly straight line. Adding a straight line helps to show there is actually a slight curve:
p = @(t) (t<0.6).*sin(t);
figure
fplot(p,[0 1])
hold on
fplot(@(t) sign(p(t)).*t,[0 1])
legend({'y = sin(t)','y = x'})
  2 comentarios
fumio hakamada
fumio hakamada el 23 de Feb. de 2024
Movida: Rik el 23 de Feb. de 2024
I had no idea about logical vector and usage of ".*". Thanks for both of you.
Rik
Rik el 23 de Feb. de 2024
You're welcome. If my answer solved your issue, please consider marking it as accepted.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Graphics Performance 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