MATLAB Answers


add the value of column from text file to the value to matrix

Asked by RUCHI CHOUDHARY on 14 Sep 2019
Latest activity Edited by Walter Roberson
on 14 Sep 2019
i create a matrix having userid as a row and itemid as a column ,now i want to add the value of the third column ,in the index value of userid,itemid.Initially fill the matrix by zeros,but now want the value associate with it.
example this is my dataset
196 242 3
186 302 3
22 377 1
196 51 2
now i want a matrix like


The third output of unique() is a relative index.
sparse(user_index_from_unique, item_index_from_unique, data(:,3))
i think my question in not clear.matrix is not square matrix so how can we sparse().In actual data file i have 973 unique user and 1683 unique item, so 973*1683 size of matrix is create in which total 10000 rows in column 3 of file is present ,which i want to store in matrix at the index loaction of user and item.possible that for loop is requred to store that data.but i don't know how to use that.
Thank you
sparse() does not require square matrices.
>> full(sparse(1:5,[1 2 3 1 2],1))
ans =
1 0 0
0 1 0
0 0 1
1 0 0
0 1 0

Sign in to comment.

1 Answer

Answer by Walter Roberson
on 14 Sep 2019
Edited by Walter Roberson
on 14 Sep 2019
 Accepted Answer

data = load('');
[uni_user, ~, uni_user_idx] = unique(data(:,1));
[uni_item, ~, uni_item_idx] = unique(data(:,2));
rating = data(:,3);
rating_matrix = sparse(uni_user_idx, uni_item_idx, rating);
This will have about 0.6% occupancy and so is well suited for a sparse matrix, but if you have particular reason, you can full() to turn it into a 12 megabyte rectangular array.


Sign in to comment.