MATLAB Answers

0

How to read a text file into a numeric array?

Asked by Mohamed Abokersh on 2 Dec 2018
Latest activity Edited by Jeremy Hughes on 2 Dec 2018
This is probably trivial, but I have not found an easy way to convert a text file charaters inside (sample attached) into a Numeric Array with n lines and m columns. I tried several function including textscan, and sscanf. However non of them could read the text file in approparte way.

  0 Comments

Sign in to comment.

1 Answer

Answer by Jeremy Hughes on 2 Dec 2018
Edited by Jeremy Hughes on 2 Dec 2018

This was a tricky one. I was able to get something in, but there are extra rows at the end that aren't importable.
This file appears to have been generated as a human readable file, so it's not surprising a machine has some trouble.
opts = delimitedTextImportOptions('Delimiter',{'\t',' '},'NumVariables',17);
opts = setvartype(opts,2:16,'double');
opts.ConsecutiveDelimitersRule = 'join';
opts.DataLines = [3, inf]; % could also be [3 38] if you don't want the trailing rows
opts.VariableNamesLine = 2;
T = readtable('ANN_month.txt',opts,'ReadVariableNames',true);
head(T)
If you need a matrix:
A = T{:,2:16};

  0 Comments

Sign in to comment.