How to put constraints to an equation[constant]?

조회 수: 6 (최근 30일)
Siddharth Sharma
Siddharth Sharma 2018년 9월 4일
댓글: Siddharth Sharma 2018년 9월 4일
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
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:

추가 답변 (1개)

John D'Errico
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])
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.

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by