Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to efficiently find and merge duplicate enteries of a vector in MATLAB?
    primarykey
    data
    text
    <p>I am writing a MATLAB code to quickly solve the following problem: Let X be a random variable distributed according to P(x), take two independent copies of X, call them X1 and X2 and find the distribution of Y = f(X1,X2) where f(,) is a known function. </p> <p>To solve the above, I start with two vectors <code>x</code> and <code>p</code> such that <code>p(i)</code> = P(<code>x(i)</code>). Suppose they both contain <code>n</code> elements. I can easily compute the <code>n</code>-by-<code>n</code> matrix <code>y</code> such that <code>y(i,j)</code> = f(<code>x(i)</code>, <code>x(j)</code>). Furthermore, I can compute the <code>n</code>-by-<code>n</code> matrix <code>p_out</code> such that <code>p_out(i,j) = p(i) * p(j)</code>. This means P(Y = <code>y(i,j)</code>) = <code>p(i,j)</code>.</p> <p>Now, if all elements of <code>y</code> are distinct we are almost done. It remains just converting the matrices to vectors and perhaps sorting them to have a nice output. Suppose we also do this by setting </p> <pre><code>y = y(:); p_out = p_out(:); [y, idx] = sort(y); p_out = p_out(idx); </code></pre> <p>The problem is, however, the elements of <code>y</code> are not typically unique. I, hence, have to merge the identical elements of <code>y</code> as follows: if <code>y(i) = y(j)</code> (remember now <code>y</code> is converted to a vector) then remove <code>y(j)</code> and set <code>p(i) = p(i) + p(j)</code>. A dirty way of doing this is using a for loop (since <code>y</code> is now sorted we only need to compare each element with its following element). However, I wonder if there exits a nicer way. </p> <p>I know that <code>unique</code> would remove the duplicated elements of a vector (hence if we only needed <code>y</code> it would be sufficient). I also know that it returns two index vectors that somehow indicate the position of duplicated elements. However, I cannot think of any nice way to use its outputs to <strong>appropriately</strong> merge the elements of <code>p</code> as well.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload