Limiting bulitin function (sine)

조회 수: 1 (최근 30일)
Roger Kalvig
Roger Kalvig 2022년 6월 13일
편집: Dyuman Joshi 2022년 6월 13일
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

채택된 답변

Dyuman Joshi
Dyuman Joshi 2022년 6월 13일
편집: Dyuman Joshi 2022년 6월 13일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by