user3137771
user3137771

Reputation: 11

How to efficiently import data from files containing a mix of numbers and strings into a Matlab cell array?

I have about thirty text files of varying dimensions in which the average is 2050x1450. As the figure shows, the first two rows are of type char indicating the number of profile and the recording time respectively. the remaining rows are values of type double.

       #1        #2       #3...........#10      #1       #2       #3......
Time 21:22:10 21:23:56 21:24:07.... 06:19:11 06:21:00 06:21:23 06:23:11......
15    0.00     0.00      0.00   ....  0.00      0.00     0.00    0.00......
30   -6.09    1200.44   32.08   .... -0.17     9.87    -44.65   768.12......
.      .         .        .     .....           .         .         .........
.      .         .        .     .....           .         .         .........
.      .         .        .     .....           .         .         .........
2050  76.009   32.98   -5.91    ..... 79.15    15.54    -87.60  -10.74 ......

with this structure, i found difficulties to assigh the content of those files into a cell array under matlab since the command 'dlmread' is conceived only for numeric data. my question is the following: how can I assigh effeciently the content of those files into the cell array?

I tested it with importdata command matlab:

PathName = uigetdir;
d = dir(fullfile(PathName,'*.txt'));
    for i = 1:numel(d)
    A(i) = importdata(fullfile(PathName, d(i).name),'\t');
end

When i execute it,I had three flow (data, text data, colheaders). My first line is all stored in a single box A(1,1).textdata{1,1}. A(1,1).textdata{1,2},...,A(1,1).textdata{1,1450} are completely empty,contrary to what I get with the second row.

Upvotes: 0

Views: 433

Answers (1)

amo
amo

Reputation: 4340

Try

A(i) = importdata(filename,' ',2)

which will give you all of the doubles in a matrix and the times in a cell array.

The first line ends up as one string. You can split that out into a matrix like so:

headerStr = strsplit(A(i).textdata{1})

strsplit is a new function in Matlab 2013. In older versions of Matlab, this should work:

headerStr = textscan(A(i).textdata{1},'%s')

You can then convert these matrices to cell arrays using num2cell

headerCells = num2cell(headerStr{1})

which will return a cell array with one string per cell

Now you have your first line of '#1' etc in headerCells, your 2nd line of times in A(i).textdata{2}, and all of your numbers in A(i).data

You can combine this into one big cell array thusly:

alldata = [[cell(1) headerCells']; A(i).textdata(2,:); num2cell(A(i).data)]

Upvotes: 1

Related Questions