user2011560
user2011560

Reputation: 75

Read a text file into matlab

I have a txt file containing multiple questions, and an answer (True / False) like this

  1. A ball is squared. F
  2. My computer is slow. T etc.

I want to make a function [Q,A] = load.test(filename) where

  1. Q = A cell array containing N strings.
  2. A = A logical vector of N elements.

I have tried different ways, but none seem to work.

[Q,A] = textread(filename,'%s %s');
This output here is the closest I've come:
     'A'
    'is'
    'F'
    'My'
    'is'
    'T'

what do I need to do ?

Upvotes: 1

Views: 122

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25242

In case you have more than one . per sentence, the solution of Silas won't work. Also you loose the dot that way. You can also do it as follows:

fid = fopen('questions.txt');
data = textscan(fid, '%s','delimiter','\n')
fclose(fid);

Q = cellfun(@(x) x(1:end-2), data{1}, 'uni',0);
A = cellfun(@(x) x(end),     data{1}, 'uni',0);

Alternatively use:

A = cellfun(@(x) x(end) == 'T',data{1});

to get the desired logical vector.


For a text file of content:

The globe is a disk. F

42 is the answer to everything. T

you get

Q{1} =  The globe is a disk.
  
Q{2} =  42 is the answer to everything.

A =

     0
     1

Upvotes: 2

Silas
Silas

Reputation: 468

According to the documentation you should use textscan instead of textread

If you know that the strings are separated by a '.' or another specific delimiter you can do

parsed = textscan(file, '%s %s', 'delimiter', '.');

Upvotes: 1

Related Questions