Clear Filters
Clear Filters

Creating composed function in MATLAB

1 view (last 30 days)
buszcini
buszcini on 16 May 2018
Answered: James Tursa on 16 May 2018
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

Answers (1)

James Tursa
James Tursa on 16 May 2018
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;

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!