How to read two words from a text file?

As the question says, what is the easiest way to read just the first two words from a text file in MATLAB? There is more data in the text file, but I don't need to read them. Bonus points if I can store them in a string easily.

 Accepted Answer

You can use fgets() to read a line and extract first two words using following code
fID = fopen(filename, 'r');
firstLine = fgets(fID);
fclose(fID);
spaceLocation = strfind(firstLine, ' ');
requiredWords = firstLine(1:spaceLocation(2)-1);
If your text file has no new lines, then you can also specify the number of character to read. For example, you only want first two words. It is safe to assume that first two words will be less than 30 characters in length. You can do it like this
firstLine = fgets(fID, 30); % replace 30 with any number you see appropriate.

4 Comments

Unfortunately that won't work. The text file is space separated, so there is more data after the first two words, and the only thing separating them is just a space.
The first two words, as you've guessed, have variable lengths, so there's no way in which I can set a fixed length or a max length because that might bring in undesired data.
I think you misunderstood my point. You need to add the line like this
fID = fopen(filename, 'r');
firstLine = fgets(fID, 100);
fclose(fID);
spaceLocation = strfind(firstLine, ' ');
requiredWords = firstLine(1:spaceLocation(2)-1);
you will still get two words at the output. I just use 30 because 2 words will be usually less than 30 characters. You can use 100 if you want, this code will still output 2 words. Have you tried ruining it?
Awesome, it works flawlessly! I'm sorry it took me a while to understand what was happening. Thanks a ton!
You are welcome.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!