Reputation: 55
I have a file containing information as follows:
id allele1 allele2
1 A A
2 T A
3 A A
. ...
. ...
. ...
I would like to parse the file into a struct array containing three fields (id, allele1, allele2)
where id are all the numbers from 1 up to n, allele1 is the first column of characters and allele2 is the second column.
I however have trouble figuring out how to go about doing this.
Upvotes: 0
Views: 739
Reputation: 1531
In the future, it would be best to show what you've tried. However, this should get you started.
fid = fopen('input.txt','r');
%header line
line = fgetl(fid);
header = regexpi(line,'\W+','split');
ID=1;
%read first line
line = fgetl(fid);
while ischar(line)
l = regexpi(line,'\W+','split');
for i=1:numel(l)
data(ID).(header{i}) = l(i);
end
ID = ID+1;
line = fgetl(fid);
end
fclose(fid);
Resulting in:
>> data
data =
1x4 struct array with fields:
id
allele1
allele2
>> data(1)
ans =
id: {'1'}
allele1: {'A'}
allele2: {'A'}
>> data(2)
ans =
id: {'2'}
allele1: {'T'}
allele2: {'A'}
Upvotes: 1