user1578688
user1578688

Reputation: 427

Extracting strings from text files in MATLAB

How can I create a new variable with values from text files, without actually loading all of them?

For example, I have two text files: the first one contains a**bc**d at line 18. The second one contains a**cf**d at the same position. The result I'm looking for is:

bc 
cf

Upvotes: 1

Views: 889

Answers (2)

Eitan T
Eitan T

Reputation: 32930

Unfortunately, your question is poorly worded, but the example provided me with clues of what you want to achieve. I hope the following helps:

Skipping lines

To skip lines, you can effectively use fgetl or fgets and discard its result. This simply advances the file pointer to the line of your desire. Regarding your simplified example, if you want to skip the first 17 lines and read the 18th, you can do as follows:

fid = fopen(somefile, 'r');
for i = 1:17
    fgetl(fid);
end
s = fgets(fid);

Or read each line into the same variable (s in my example), overriding its previous value:

fid = fopen(somefile, 'r');
for i = 1:18
    s = fgetl(fid);
end

An even shorter alternative is to this is to employ textscan with the 'HeaderLines' option:

C = textscan(fid, '%s', 1, 'Delimiter', '\n', 'HeaderLines', 17);
s = C{:};

Extracting a substring from a string

Since a string is an array (vector) of characters, you can use vector indexing to extract any elements you want. For example, to extract positions 2 and 3 from s = 'abcd' to obtain bc, you can use the expression s([2 3]), like so:

result = s([2 3])

Upvotes: 3

Brett Shoelson
Brett Shoelson

Reputation: 326

I'm not sure I understand your question, but you might want to look at the documentation for FSEEK and FGETL. Brett

Upvotes: 1

Related Questions