質問

I have one matrix *u_test* that contains the data from my test set. It's formats is like that:

X  y  value
1  3  5.0
1  6  3.4
4  3  2.0

I want to create a matrix test from *u_test*, so that the value of the rating is in it correct position, for example:

   1    2    3    4    5    6

1:          5.0 
2:                         3.4
3:
4:          2.0

Is there a loop-free way to do this?

役に立ちましたか?

解決

The easiest way is to use SPARSE

out = sparse(u_test(:,1),u_test(:,2),u_test(:,3));

If the target size of the array should be m-by-n, you can write instead

out = sparse(u_test(:,1),u_test(:,2),u_test(:,3),m,n);

The good thing about using sparse is that it won't take too much space if the matrix u_test is large. However, if for some reason you cannot use sparse, convert to a full matrix using

outNotSparse = full(out);

他のヒント

A fairly simple way would use the function sub2ind:

A = [1 3 5; 1 6 2; 4 3 2];

maxima = max(A(:,1:2));
xsub = A(:,1);
ysub = A(:,2);

index = sub2ind(maxima, xsub, ysub);

C = zeros(maxima);
C(index) = A(:,3);

This parses out the three columns of A and converts the first two into linear indices. These are simply used to assign your data to the proper spots in C.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top