Limiting bulitin function (sine)

2 views (last 30 days)
Roger Kalvig
Roger Kalvig on 13 Jun 2022
Edited: Dyuman Joshi on 13 Jun 2022
I have the following problem in matlab:
i need to create a function (well, it is rather relationship between x and y than function) which should look like this:
function y = fcn(x)
Bext = 0.6;
G = 10.553;
if x < 0
y = 0;
elseif x == 0
y = 10^10;
elseif x == 180
y = 10^10;
elseif x > 180
y = 0;
else
y = 1./(G.*Bext.*(sind(x)));
end
end
Basically, for all x below 0 y should be 0, the same in case of x larger than 180. For all x in the range 1-179 i need to have a function 1/sin(x), and for x=0 and x=180 which is infinity(singularity) for the function 1/sin(x) i set the cap like 10^10 (any big number different than infinity will do). Here I treat x as an angle and I work with angle step deltax=1.
As far as I know the code above correctly computes y for any given x. The problem begins when I want to work on a range of x values, even simple plotting :
x=-10:200;
plot(x,fcn(x))
shows the function 1/sin(x) exists even outside the range (x=1:179) defined in the simple code above.
So the question is why I still see the function y=1/sin(x) where it should be y=0 and how to limit/bound the function to the defined range.
Thanks for help in advance.
Roger Kalvig

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 13 Jun 2022
Edited: Dyuman Joshi on 13 Jun 2022
You have to call your function for each value of x and store it in another variable and then plot it, as your function is defined to calculate for a singular value of input, not an array/matrix.
x=-10:200;
y=arrayfun(@fcn, x); %you can use a for loop as well
plot(x,y)
function y = fcn(x)
Bext = 0.6;
G = 10.553;
if x < 0
y = 0;
elseif x == 0
y = 10^10;
elseif x == 180
y = 10^10;
elseif x > 180
y = 0;
else
y = 1./(G.*Bext.*(sind(x)));
end
end

More Answers (0)

Categories

Find more on Performance and Memory 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!