我有一个矩阵 *u_test* ,其中包含来自我的测试集的数据。它的格式是这样的:
X y value
1 3 5.0
1 6 3.4
4 3 2.0
我想从 *u_test* 创建一个矩阵测试,以便评级的值位于正确的位置,例如:
1 2 3 4 5 6
1: 5.0
2: 3.4
3:
4: 2.0
有没有一种无循环的方法来做到这一点?
最简单的方法是使用SPARSE
out = sparse(u_test(:,1),u_test(:,2),u_test(:,3));
如果数组的目标大小应该是m-by-n,则可以改为
out = sparse(u_test(:,1),u_test(:,2),u_test(:,3),m,n);
使用稀疏的好处是,如果矩阵很大,它不会占用太多空间u_test。但是,如果由于某种原因您不能使用稀疏矩阵,请使用转换为完整矩阵
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.