user3658425
user3658425

Reputation: 119

Reading data file with rows of variable sizes

I have a data file containing rows of variable sizes:

16 54 1 -3 5
15 5
1 9 10 5

How can I load it into a cell array data so that

data{1} = [16 54 1 -3 5]; 
data{2} = [15 5]; 
data{3} = [1 9 10 5];

?

Upvotes: 1

Views: 49

Answers (2)

Divakar
Divakar

Reputation: 221564

You can try impordata appproach that is short and concise -

%// Assuming filepath1 is the path to your file
data = cellfun(@str2num,importdata(filepath1,'%s'),'uni',0)

You can visualize the data, using celldisp tool that displays contents of a cell array, like this - celldisp(data). The output would be -

data{1} = 
    16    54     1    -3     5

data{2} =
    15     5

data{3} = 
     1     9    10     5

Upvotes: 2

Franck Dernoncourt
Franck Dernoncourt

Reputation: 83177

Let data.txt contains

16 54 1 -3 5
15 5
1 9 10 5

You can read it into a cell array data with the following:

fid = fopen('datatest.txt');
allData = textscan(fid,'%s','Delimiter','\n');
data = cellfun(@str2num, allData{1}, 'UniformOutput', false);
fclose(fid);

>> data = 

ans =    

[1x5 double]
[1x2 double]
[1x4 double]

>> data{1}

ans =

    16    54     1    -3     5

Upvotes: 2

Related Questions