How to add two probability density functions efficiently

5 ビュー (過去 30 日間)
Juan Pablo Segovia
Juan Pablo Segovia 2017 年 12 月 19 日
コメント済み: David Goodmanson 2017 年 12 月 20 日
Hello,       I have a simple problem but I need to improve the execution efficiency when I have thousands of data in a probability density function, a small example:
close all
clear
%example
x =[ 1 3 5 9 15];
y =[ 4 7 8 12 6];
xn=[ 3 9 16];
yn=[ 10 3 4];
[xnew,ynew]=add2pdf(x,y,xn,yn);
xnew
ynew
% function
function [xnew,ynew]=add2pdf(x,y,xn,yn)
% sum two probability density function
[nf,nc]=size(xn);
xold=x;
yold=y;
xx=[x xn];
[xv,xp]=sort(xx,'ascend');
dxv=diff(xv);
xnew=[xv(1) xv(find(dxv>0)+1)];
ynew=zeros(1,length(xnew));
for i=1:size(y,2),
pynew=find(xnew==xold(i)); % <====this instruction it's very slow (find), but I need the pointers
ynew(pynew)=y(i);
end
for i=1:length(xn),
px=find(xnew==xn(i));
ynew(px)=ynew(px)+yn(i);
end
return

採用された回答

David Goodmanson
David Goodmanson 2017 年 12 月 20 日
編集済み: David Goodmanson 2017 年 12 月 20 日
Hi Juan,
Here is one way. It takes advantage of the fact that when you make a sparse matrix with repeated indices, the corresponding values get added. Here M is a one-row matrix.
M = full(sparse([x xn],1,[y yn]))';
xnew = find(M);
ynew = M(xnew);
  3 件のコメント
Juan Pablo Segovia
Juan Pablo Segovia 2017 年 12 月 20 日
David, Great solution for integers numbers, fast, efficient and elegant. Thank you very much.
David Goodmanson
David Goodmanson 2017 年 12 月 20 日
Juan, you're welcome, thank you for your comment. The sparse function has useful properties and did most of the work here.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by