0

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.

1 Answer 1

1

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'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.