Hi all,
I am trying to read a sparse matrix from a notepad.. I tried with the following matrix however, it's not given the correct sparse matrix:
clear all
clc
M=readmatrix('S_sp.dat');
I would like to the output to be as:
(1,1) 5.7744185
(1,2) 0.00
and so on...
I understand sprase should be without zero, but I need to read the file as it is , and be in a sparse format
I already attached the file in a zip folder

댓글 수: 2

James Tursa
James Tursa 2022년 1월 18일
편집: James Tursa 2022년 1월 18일
Can you provide a small sample of numbers in a txt or mat file instead of a zip file? Also, the sparse format in MATLAB does not store 0's. Trying to create such a matrix, even using hacks, would only result in an invalid sparse matrix and would violate assumptions made in background sparse matrix operations. Why do you think you need to physically store 0's in your sparse matrix?
Normally one would read in the data and then generate the sparse matrix from this data, which unfortunately results in two copies of the data in memory. The only ways I know of to read data directly into a sparse matrix would be to use a mex routine or to have the data in a mat file (e.g., text version) already in sparse format. Is the size of the matrix and the number of elements known prior to reading the elements?
Mark Sc
Mark Sc 2022년 1월 18일
@James Tursa Thank you so much for your comment,
I upload in .txt
The data in the file already sparse, I need to write it same, but with same format of sparse in matlab so I could use it later,
Hope you could help me...
Thank you,

댓글을 달려면 로그인하십시오.

 채택된 답변

Matt J
Matt J 2022년 1월 18일

0 개 추천

S=spconvert(load('S_sp.txt'))

댓글 수: 5

Mark Sc
Mark Sc 2022년 1월 18일
It works fine, even it reads without zero, but read in a sparse format,
just a small question, is it possible to return the sparse matrix to dense ?
I mean is that possible to read the sparse matrix as normal matrix also
Thank you
James Tursa
James Tursa 2022년 1월 19일
편집: James Tursa 2022년 1월 19일
Probably easiest to just convert the sparse matrix:
full(S)
Or, if all of the elements are present exactly once in the file in the order you show, you could simply reshape and transpose the third column of the matrix obtained from loading the text file.
I would do,
T=load('S_sp.txt');
S=accumarray(T(:,1:2), T(:,3));
Mark Sc
Mark Sc 2022년 1월 19일
@Matt J and @James Tursa Thank you both so much
James Tursa
James Tursa 2022년 1월 20일
Note that these methods still have two copies of the data in memory, but as stated previously this probably can't be avoided in your case unless you resort to a mex routine.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2022년 1월 18일

댓글:

2022년 1월 20일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by