How to use 'if' and 'else' function for equations that are different for a range of x
12 views (last 30 days)
Show older comments
A periodic function with period 1 is defined on the interval 0 < x < 1 by
f(x) = x^2 for 0 <= x <= 0.5 and, f(x) = 0.5*(1-x) for 0.5 <= x <= 1
We are asked to write a function that can plot a graph of x against f. This is for a range of x values so I used linspace to create many x values but the && function I then use does not work for vectors. The script I used is below but won't allow me to use && and if I use just & the graph is wrong. I know this because at x=0, f should equal 0 but is plotted as 0.5 so is using the wrong equation at this point.
x=[0:.01:1]; if 0 <= x && x <= 0.5 f=x^2; else f=0.5*(1-x) end plot(x,f)
0 Comments
Answers (1)
Wayne King
on 11 Dec 2013
Edited: Wayne King
on 11 Dec 2013
Use logical indexing:
So for example:
x = 0:0.01:1;
f = zeros(length(x),1);
f(x>=0 & x<=0.5) = x(x>=0 & x<=0.5).^2;
Now you complete the rest. The part >0.5
0 Comments
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!