Matlab converts sparse matrix representation to sparse matrix

Matlab converts sparse matrix representation to sparse matrix

Problem description

I now have a map data set, the data set is wiki,
wiki data set
but the author is given a sparse matrix representation, but I do not want to use the sparse representation, I want the feature matrix, nothing found A very straightforward method. I have summarized a method through Baidu. I will record it below so that I can check and encounter the same problem in the future.
#In simple terms, the problem is that the data is originally like this, Insert picture description here
but I want to get the data representation matrix like this: Insert picture description here
Of course, the latter is the data I have processed. Since I have not used matlab much, it is more watery, but now you see Here, you should not be good at it, haha. The code is directly below

The first step is to read the original data and save it with three matrices.

[b,c,d]=textread('/Users/yangyangyang/Downloads/tfidf.txt','%d %.6f %.6f')

This is the obtained data:
Insert picture description here
that is, the original data is a matrix of 1556595*3. Bcd disassembled it. b is the stored row, c is the column, and d is the value corresponding to the current row and column. Then the next thing to do is to create a new matrix to store the sparse matrix representation, and then write the new matrix to the txt file.

[e,f]=size(b)%获取长度,也就是1556595,为了遍历,e里面就是存的长度,f就是列维度1而已
while(f<=e)
m=b(f,1)+1;
n=c(f,1)+1;
a(m,n)=d(f,1);
f=f+1;
end    

In this way, the matrix a is successfully established. Insert picture description here
Here I did not initialize a, but a defaults to 0. The next step is to save the data in a txt file.

fid=fopen(['/Users/yang/Desktop/','out.txt'],'w');%写入文件路径
[r,c]=size(a);            % 得到矩阵的行数和列数
 for i=1:r
  for j=1:c
  fprintf(fid,'%9.8f ',a(i,j));%9.8f后面有个空格,你加\t,数据之间间距更大
  end
  fprintf(fid,'\n'); %换行
 end
fclose(fid);

In this way, a txt file named out is generated on your desktop, which contains the stored a matrix.

Guess you like

Origin blog.csdn.net/Asure_AI/article/details/109435967