3

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?

plesiv
  • 6,935
  • 3
  • 26
  • 34
ARAT
  • 884
  • 1
  • 14
  • 35

1 Answers1

4

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)).
plesiv
  • 6,935
  • 3
  • 26
  • 34
  • 1
    thank you so much! it did work! but can you explain me why this simple code changes everything? – ARAT Nov 09 '12 at 13:51
  • @MuratArat I've provided an explanation! – plesiv Nov 09 '12 at 14:03
  • But, x=0:1:8, does not create the vector x =[0 1 2 3 4 5 6 7 8] ? – ARAT Nov 10 '12 at 13:22
  • You meant to say that `x=0:1:8` didn't create `x=[0 1 2 3 4 5 6 7 8 9]` I suppose... You were right; I made mistake which is fixed now! – plesiv Nov 10 '12 at 15:05
  • yes, ok, sorry for bothering you, I was almost aware of that mistake, but as I said, I am so new to coding so I thought there was a feature that I don't know. Much obliged for your help. – ARAT Nov 10 '12 at 16:41