Reputation: 31
There are many questions on topics of text files and cell arrays but none is related to the problem that I am facing. I have a text file with numeric data like this:
1,2,3,4,5
6,7,8
9,10,11,12,13,14,15
I want this text to be put into a cell array with dimensions
[1X5]
[1X3]
[1X7]
I have tried csvread but it makes a matrix and all void elements are set to 0, which is not what I want. I'd be thankful for some help, please.
Upvotes: 1
Views: 152
Reputation: 221504
You can try an importdata
based approach, assuming data.txt
to be your input text-file.
data1 = importdata('data.txt','')
You would get -
data1 =
'1,2,3,4,5'
'6,7,8'
'9,10,11,12,13,14,15'
and then -
out = cellfun(@(x) str2num(char(strsplit(x,',')))',data1,'uni',0)
You would get your desired output -
out =
[1x5 double]
[1x3 double]
[1x7 double]
You can display their values with celldisp(out)
-
out{1} =
1 2 3 4 5
out{2} =
6 7 8
out{3} =
9 10 11 12 13 14 15
Upvotes: 1
Reputation: 112659
Use textread
, specifying that empty cells be filled with NaN
:
>> data = textread('data.txt', '', 'delimiter', ',' ,'emptyvalue', NaN)
data =
1 2 3 4 5 NaN NaN
6 7 8 NaN NaN NaN NaN
9 10 11 12 13 14 15
Then convert each row excluding NaN
's into a cell:
>> data = arrayfun(@(n) data(n,~isnan(data(n,:))), 1:size(data,1), 'uni', 0)
data =
[1x5 double] [1x3 double] [1x7 double]
>> celldisp(data)
data{1} =
1 2 3 4 5
data{2} =
6 7 8
data{3} =
9 10 11 12 13 14 15
Upvotes: 1