Creating composed function in MATLAB

1 次查看(过去 30 天)
Excuse me, English is not my native language and I can't seem to find right word for this kind of function (composed is one that fits my language) I mean one like this:
y=cos(x) when x=(-∞;0>
y=sin(x) when x=(0;+)
I'm new to MATLAB, I tried to practice by creating few basic graphs for my assignment, but I've failed
for example I create linspace from 0 to 100, then I want to do this:
if x<30 - y=cos(x)
elseif x>=30 & x<50 - y=sin(x)
elseif x>=50 y=x.^2
I would be very grateful for some help

回答(1 个)

James Tursa
James Tursa 2018-5-16
E.g., vectorized code using logical indexing:
y = zeros(size(x));
g = x <= 0;
y(g) = cos(x(g));
y(~g) = sin(x(~g));
And for the 2nd set:
y = zeros(size(x));
g1 = x < 30;
g2 = x >= 30 & x < 50;
g3 = x >= 50;
y(g1) = cos(x(g1));
y(g2) = sin(x(g2));
y(g3) = x(g3).^2;

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by