How to put constraints to an equation[constant]?
2 次查看(过去 30 天)
显示 更早的评论
I want to put constraints to this uniform distribution function,
f(x)=1/2 if 2<=x<=4,
0 otherwise
I am asked to write my own uniform distribution function, so I can't use the in built function.
I'm using syms so as to plot, but when I use the if statement it says "conversion of syms to logical form is not possible". I want to make a pdf but the only result I need is the graph.
Thank You, all the three functions are right. I do not know which one to choose as the best answer.
采纳的回答
Dimitris Kalogiros
2018-9-4
My suggestion:
clear; clc;
syms x
f(x)=piecewise((2<=x & x<=4), 1/2, 0)
fplot(f(x), 'LineWidth', 3);
xlabel('x'); ylabel('f(x)');
zoom on; grid on;
If you run the script (provided that you have symbolic math toolbox), you will receive:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/194945/image.jpeg)
更多回答(1 个)
John D'Errico
2018-9-4
编辑:John D'Errico
2018-9-4
It depends on what you want to do with it. If you just want to create a function that returns 1/2 in the interval x>=2 & x<=4, it is easy. If you are trying to create a PDF from that, well again, it depends.
But this is easy, and easy to write in a nice, vectorized form. No loops are needed, nor any special functions as long as you understand how MATLAB does tests and what a comparison returns.
f = @(x) ((x>=2) & (x<=4))/2;
Does it work? Of course. The test (x>=2) returns a boolean result, 1 where that is true, 0 where false. The same applies to the second test. Then I divide by 2, which casts the logical result from those tests into a double.
x = 0:.5:5;
[x;f(x)]
ans =
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
0 0 0 0 0.5 0.5 0.5 0.5 0.5 0 0
You can plot the function, etc.
ezplot(f,[0,5])
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/194949/image.jpeg)
I might also have written it using a multiply.
f = @(x) (x>=2) .* (x<=4)/2;
I dropped the extra set of parens there, which were necessary when I used the & operator in the first case, due to an issue with operator precedence rules. Whenever you are unsure about operator precedence, it never hurts to throw in an extra set of parens. It may also help to make your code easier to follow, as long as you don't overdo the parens.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Special Values 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!