LiamNeesonFan
LiamNeesonFan

Reputation: 2813

How to read data from a text file into a matrix in MATLAB

I'm having difficulty reading my .txt file into a single matrix with the rows and columns show in the text below in MATLAB.

%Q1 Q2 Q3 Q4 Q5
42 90 55 25 32
23 55 70 89 53

How would I create a single matrix with only the numbers from that text file? The values are delimited by spaces. There are 19 rows, but I want to be able to read it with an arbitrary number of rows and columns in case of changes. I tried using textscan and fscanf but no luck so far. Thanks for the help.

Upvotes: 3

Views: 11890

Answers (1)

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

The best command to load in a matrix from a text file is the load command. Specifically, the file must meet the following criteria:

  1. The first lines can include text, but they must include a % as the first character, otherwise it will not work. The % acts as a comment value.
  2. The values in the data portion of the file must be in a matrix format, with a deliminator in between. Each row will be a row of the matrix.

So, I could read in a file like this:

%Q1 Q2 Q3
1 2 3
4 5 6
7 8 9

by simply calling a load command on the filename. IE, if it's called test.txt, I call blah=load('test.txt') The same command would read in the matrix you have included, or any arbitrary matrix.

Alternatively, you could look at reading one line in at a time, and searching for the end of the file. The command is fgetl.

Upvotes: 7

Related Questions