MATLAB: Importing data from a txt file that is laid out in matrix form

data importdelimitersimportdataimporting text dataMATLABtext filetextscan

I have a text file which has data laid out in the following format:
a11 a12 a13 a14 a15 a16
a21 a22 a23 a24 a25 a26
a31 a32 a33
a41 a42 a43 a44 a45 a46
a51 a52 a53 a54
I would like to import this data and preserve the formatting. How can I do this?

Best Answer

Set the path to your text file and the number of columns in your text file. This will preserve the format of your data and store all elements in a cell array. Missing values in your text file will be missing values in the cell array.
Note that this will not work if there is a missing value in the first row.
filename = 'C:\Users\boykoborisov\Documents\MATLAB\mydata.txt'; %your text file
nCols = 6; %number of columns in your data
fid = fopen(filename); % open the text file
C = textscan(fid, repmat('%s ', 1, nCols)); % read text file
fclose(fid); % close text file
nRows = cellfun(@length, C); % number of rows for each column
data = cell(max(nRows), nCols); % define new cell array that will store your data
for i = 1:nCols
data(1:nRows(i),i) = C{i};
end
data =
5×6 cell array
{'a11'} {'a12'} {'a13'} {'a14' } {'a15' } {'a16' }
{'a21'} {'a22'} {'a23'} {'a24' } {'a25' } {'a26' }
{'a31'} {'a32'} {'a33'} {0×0 char} {0×0 char } {0×0 char }
{'a41'} {'a42'} {'a43'} {'a44' } {'a45' } {'a46' }
{'a51'} {'a52'} {'a53'} {'a54' } {0×0 double} {0×0 double}
Related Question