Let's do what you say in the question step by step:
For each unique value in
A(:, 2)
:[U, ia, iu] = unique(A(:, 2));
Take the corresponding values in
A(:, 1)
and look for their value inC
:[tf, loc] = ismember(A(:, 1), C);
It's also recommended to make sure, just in case, that all values are actually found in
C
:assert(all(tf))
Then take the relevant rows in
B
and compute their mean:[X, Y] = meshgrid(1:size(B, 2), iu); result = accumarray([Y(:), X(:)], reshape(B(loc, :), 1, []), [], @mean);
Hope this helps! :)
Example
%// Sample input
A = [1 2 ; 3 2; 4 7; 10 2; 6 7; 10 9];
B = [1 2 3; 4 4 9; 1 8 0; 3 7 9; 3 6 8];
C = [4; 10; 6; 3; 1];
%// Compute means
[U, ia, iu] = unique(A(:, 2));
[tf, loc] = ismember(A(:, 1), C);
[X, Y] = meshgrid(1:size(B, 2), iu);
result = accumarray([Y(:), X(:)], reshape(B(loc, :), [], 1), [], @mean);
The result is:
result =
3.3333 5.6667 8.6667
1.0000 5.0000 1.5000
4.0000 4.0000 9.0000