how to write this data into a sparse matrix
1 次查看(过去 30 天)
显示 更早的评论
Dear All,
I have this data which is represent 0,1 matrix. it is given in this way. the first element 12,4,3,18,19,10 means the number of position of the ones in this row. I want to create a sparse matrix for it. can anyone help me with it?
12 1 2 3 4 60 61 62 63 89 90 91 95
4 32 33 34 35
3 83 84 91
18 39 40 41 42 43 71 72 73 74 75 76 77 88 90 92 93 94 95
19 29 30 31 32 33 34 35 36 37 79 80 81 83 84 85 86 87 88 89
10 73 86 87 88 89 90 91 92 93 94
the final matrix should have size 6x95. I appreciate any help.
regards,
Nadia
4 个评论
Stephen23
2016-2-29
Please edit your question and upload your exact data: click the paperclip button, then both Choose file and Attach file buttons.
Stephen23
2016-2-29
编辑:Stephen23
2016-2-29
How did you get all of these lines of numbers into this text file? Did you copy-and-paste them from some source? If so, what source? It may be easier to simply get MATLAB to read the data directly from that source.
The answer really depends on you: do you want a general solution that will also work for other data, or are you wanting to process only this data?
采纳的回答
Guillaume
2016-2-29
columns = {[12 1 2 3 4 60 61 62 63 89 90 91 95]
[4 32 33 34 35]
[3 83 84 91]
[18 39 40 41 42 43 71 72 73 74 75 76 77 88 90 92 93 94 95]
[19 29 30 31 32 33 34 35 36 37 79 80 81 83 84 85 86 87 88 89]
[10 73 86 87 88 89 90 91 92 93 94]}
rows = arrayfun(@(row) repmat(row, 1, numel(columns{row})), 1:numel(columns), 'UniformOutput', false);
out = sparse([rows{:}], [columns{:}], 1)
7 个评论
Guillaume
2016-2-29
Yes, I saw your m file. This is not the origin of your data obviously. That m file is not very useful as it can't be interpreted by matlab.
The simplest thing is for you to edit that file to remove the first row and edit the 2nd row so it's just the numbers. Once you've done that you can then import the data into matlab with the code I've given:
filecontent = fileread('data.m');
columns = cellfun(@str2num, strsplit(filecontent, {'\n', '\r'}), 'UniformOutput', false);
%remove the 1st number in each row
columns = cellfun(@(c) c(2:end), columns, 'UniformOutput', false);
%same code as before
rows = arrayfun(@(row) repmat(row, 1, numel(columns{row})),
1:numel(columns), 'UniformOutput', false);
out = sparse([rows{:}], [columns{:}], 1)
Note that I would change the extension of the file to '.txt' as it's not a proper m file, but that does not matter for the code.
because I want to use fprintf: that's totally irrelevant. Importing the data is a different task from displaying it.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!