vosvi
vosvi

Reputation: 5

Reading a text file with varying length of lines

I have a data file (.txt) which is as follows;

A 2.2 5
B 3.2 0.5
C 0 2
A 3 2 B
A 2 6 C
B 2.3 4.5 C

First three are representing the nodes (name, feature1, feature2) whereas the last three are representing the relation between each node (node A, node B, node C). And as you see, nodes and relations are in different format (nodes=string numeric numeric whereas relations=string, numeric numeric string). At the end I will plot them based on their initial features and relations through time. I tried couple of things but the thing that nodes have 3 parameters and edges have 4 parameters makes it difficult to solve.

So, basically, I want to read the text file line by line and I would like to be able to define all the nodes and have all the parameters of the nodes as string numeric numeric and define all the relations as well to plot them in the end.

Any help is appreciated.

Upvotes: 0

Views: 96

Answers (1)

craigim
craigim

Reputation: 3914

check out the built-in function fgetl.

fid = fopen(filename);

lineoftext = fgetl(fid);
while ischar(lineoftext)
    C = strsplit(strtrim(lineoftext)); % this will be a cell array
    if length(C) == 3
        % then it's a node, put code here
    else
        % then it's relational, put code here
    end
    lineoftext = fgetl(fid);
end

fclose(fid);

This will read a single line from the file, split it into chunks of text in a cell array, and then count the number of chunks to see if it's a node or a relation string. You'll have to put your own code inside the if statements. Then it reads in another line and does it all over again. When it reaches the end of the file, lineoftext = -1 and the while loop ends.

Upvotes: 1

Related Questions