Reputation: 427
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
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:
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{:};
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
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