Question

I want to draw some plots in Matlab.

Details: For class 1, p(x|c1) is uniform for x between [2, 4] with the parameters a = 1 and b = 4. For class 2, p(x|c2) is exponential with parameter lambda = 1. Besides p(c1) = p(c2) = 0.5 I would like to draw a sketch of the two class densities multiplied by P(c1) and P(c2) respectively, as a function of x, clearly showing the optimal decision boundary (or boundaries).

I have the solution for this problem, this is what the writer did (and I want to get), but there's no Matlab code, so I want to do it all by myself.

IMAGE 1

And this is what I drew.

IMAGE 2

And this is the MATLAB code I wrote.

x=0:1:8;

pc1 = 0.5;
px_given_c1 = exppdf(x,1);
px_given_c2 = unifpdf(x,2,4);

figure;
plot(x,px_given_c1,'g','linewidth',3);
hold on;
plot(x,px_given_c2,'r','linewidth',3);
axis([0 8 0 0.5]);
legend('P(x|c_1)','P(x|c_2)');

figure;
plot(x,px_given_c1.*pc1,'g','linewidth',3);
hold on;
plot(x,px_given_c2.*(1-pc1),'r','linewidth',3);
axis([0 8 0 0.5]);
legend('P(x|c_1)P(c_1)','P(x|c_2)P(c_2)');

As you can see, they are almost smiliar, but I am having problem with this uniform distribution, which is drawn in red. How can I change it?

Was it helpful?

Solution

You should probably change x=0:1:8; to something like x=0:1e-3:8; or even x=linspace(0,8,1000); to have finer plotting. This increases number of points in vectors (and therefore line segments) Matlab will use to plot.


Explanation: Matlab works with line segments when it does plotting!

By writing x=0:1:8; you create vector [0 1 2 3 4 5 6 7 8] that is of length 9, and by applying exppdf and unifpdf respectively you create two vectors of the same length derived from original vector. So basically you get vectors [exppdf(0) exppdf(1) ... exppdf(8)] and [unifpdf(0) unifpdf(1) ... unifpdf(8)].

When you issue plot command afterwards Matlab plots only line segments (8 of them in this case because there are 9 points):

  • from (x(1), px_given_c1(1)) to (x(2), px_given_c1(2)),
  • ...
  • from (x(8), px_given_c1(8)) to (x(9), px_given_c1(9)).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top