how can I separate the rows of text file?

3 次查看(过去 30 天)
Hi I want to pick the specific row or column data but the problem is that text file is not saved as I wanted
For example
3 4 5 2
4 1
4 5 6 7
2 1
2 3 4 5
6 7
1 5 3 5
2 4
2 3 5 6
7 8
2 1 3 4
5 6
Even though the matrix is 6 by 6, it is saved like the above. So How can I read this txt file as 6 by 6 matrix

回答(1 个)

Dan Klemfuss
Dan Klemfuss 2018-1-24
Hello Jungbae. This isn't the most elegant solution, but it'll do the trick if you just need to repeat this task. Just replace the 'your_file_name.txt' with whatever you've named your file.
fileID = 'your_file_name.txt';
raw = fileread(fileID); % Read in file as characters
raw = strrep(raw,sprintf('\n'),''); % Remove newline characters
raw = strrep(raw,sprintf('\r'),' '); % Replace carriage returns with spaces
raw = strrep(raw,sprintf(' '),' '); % Remove any double spaces leftover
val = reshape(str2num(strrep(raw,sprintf(' '),' ')),[6,6]); % Create a 6x6 numeric array
Please let me know if you have any questions!

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by