Calculating PDF from data set

50 views (last 30 days)
I have a random variable k whose size is (1000*1), I want to draw a PDF curve for its values over a range x.
I tried this line:
pdf_normal = pdf('Normal',k,x);
But it return an array all of its values are NaN.
How can I fix that? or is there another way to get what I want?
Note:
k and x have the same size.

Accepted Answer

Star Strider
Star Strider on 14 Sep 2020
That is likely not the appropriate initial function. The fitdist function would likely do what you want. Then, use the pdf function on the output of fitdist.
Example —
k = randn(1000,1); % Create ‘k’
x = linspace(-5,5); % Create ‘x’
pd = fitdist(k, 'Normal');
y = pdf(pd,x);
figure
plot(x, y)
grid
xlabel('x')
ylabel('PDF')
.
  4 Comments
Hazem Al-Bulqini
Hazem Al-Bulqini on 14 Sep 2020
I'm doing it inside a loop. Sometimes it returns NaN values.. why?
And if I am to skip these NaN, how to exclude these colums from my cell array?
Star Strider
Star Strider on 14 Sep 2020
The problem here is that fitdist will not accept an empty argument (my first approach was to simply set those cells to []), so in order to make it compatible, I set the NaN cells to eps. (You can set them to something else if you want to.) You can then trap them and eliminate them before sending them to fitdist.
To reset the NaN cells:
for k1 = 1:size(B,2)
Bidx = cellfun(@(x)~isnan(x), B{k1}, 'UniformOutput',0);
for k2 = 1:size(Bidx,2)
if all(Bidx{k2} == 0)
Bnew{k1}{k2} = cell2mat(Bidx(k2))+eps;
else
Bnew{k1}{k2} = B{k1}{cell2mat(Bidx(k2))};
end
end
end
That appears to work with the test cell array I created to test my code.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!