1
votes

I’m wondering how I can combine vectors in MATLAB in the following way: I have a vector

S= [0.1 0.2 0.1 0.3 0.1 0.5 1 3]

And a second vector with same length

B= [1 1 4 4 6 7 9 10]

Now I would need to have a vector A with as many elements as the potential numbers in B (in this example e.g 10) and this vector should contain the value of S when B’s content equals the index of A. And if there are several potential S values it should contain the mean of those. If there is no value in B that equals th index of A, A should contain Na.

So in this example

A= [0.15 NaN NaN 0.2 NaN 0.1 0.5 NaN 1 3]
2
This sound a lot like an XY problem to me. What are you really trying to do? - Bernhard

2 Answers

0
votes

You can loop through and compute the mean for all indices between 1 and max(B). You can extract the elements of S to average using logical indexing (S(B == k)). Also, the mean of an empty array (mean([])) is always going to yield a NaN so that will create NaN values automatically for you in the cases where B doesn't contain a particular index.

A = arrayfun(@(k)mean(S(B == k)), 1:max(B))

%  0.1500   NaN   NaN   0.2000   NaN   0.1000   0.5000  NaN  1.0000  3.0000

If we break that down into a for loop it would look something like this

for k = 1:max(B)
    % Find elements of B that contain this value of k
    touse = B == k;

    % Grab elements of S that correspond to these entries in B
    svalues = S(touse);

    % Now take the average and store it in our result. 
    % If svalues is empty, then this will be a NaN
    A(k) = mean(svalues);
end

If we want this to be more general we would probably want to make the range min(B):max(B) rather than 1:max(B)

A = arrayfun(@(k)mean(S(B == k)), min(B):max(B));
0
votes

That's what accumarray does:

A = accumarray(B(:), S(:), [], @mean, NaN).';

The third input, [], specifies that the size of the result should be the minimum possible, determined by maximum value of B. The fourth input, @mean, specifies the function to apply to each group of elements from S determined by each value of B. The fifth input, NaN, is the fill value.