简体   繁体   中英

Matlab create matrix from data of other matrix

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM