MATLAB: How to fill a matrix column with dta coming from another matrix according to index

filling data

I need to fill a large matrix with data coming from a smaller matrix. Both matrices contains a first column with an index and a second column with the results of an experiment. I need to combine the results according to their index. For example I have a matrix A:
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
And a matrix B
1 10
2 10
4 10
7 10
I would like to combine them to obtain the matrix C with 3 columns (column 1 for index, column 2 results from A, column 3 results from B)
1 1 10
2 1 10
3 1 NaN
4 1 10
5 1 NaN
6 1 NaN
7 1 10
8 1 NaN
9 1 NaN
I have to do that on matrices with millions of rows, therefore methods limiting calculation time would be welcome. Thank you very much for any help.

Best Answer

Without knowing the size of the matrix, it might be a good idea to use a sparse matrix, instead of filling the non existant elements with NaN. Now, this is not exactly what you did, but it will give you a good hint of what you can accomplish with a sparse structure.
I did this fairly quick, because it is late where I live, but it should work fine
%create the example vectors
A = [(1:9)',ones(9,1)];
B = [1,2,4,7]';
B = [B, 10+0*B];
%putting the data into a sparse matrix
M = sparse([]);
M(A(:,1), 1) = A(:,2);
M(B(:,1), 2) = B(:,2);
Note that I use the first column in A as an index in M and the same goes for B. When I add the elements I add them in the first column of M, then the second column, separating where the values come frome.
I hope this helps.