Search code examples
matlabmatrixoctavefile-read

How to read a file containing numbers in Octave using textscan


I am trying to import data from text file named xMat.txt which has the data in the following format.

200 space separated elements in one line and some 767 lines.

This is how xMat.txt looks.

386.0 386.0 388.0 394.0 402.0 413.0 ... .0 800.0 799.0 796
801.0 799.0 799.0 802.0 802.0 80 ... 399.0 397.0 394.0 391
.
.
.

This is my file - for reference.

When I try to read the file using

file = fopen('xMat.txt','r')
c = textscan(file,'%f');

I get the output as:

> c =  {   [1,1] =
>       386
>       386
>       388
>       394
>       402
>       413
>       427
>       442
>       458
>       473
>       487
>       499
>       509
>       517
>       524 ... in column format

What I need is a matrix of size (767X200). How can I do this?


Solution

  • I wouldn't use textscan in this case because your text file is purely numeric. Your text file contains 767 rows of 200 numbers per row where each number is delimited by a space. You couldn't get it to be any better suited for use with dlmread (MATLAB doc, Octave doc). dlmread can do this for you in one go:

    c = dlmread('xMat.txt');  
    

    c will contain a 767 x 200 array for you that contains the data stored in the text file xMat.txt. Hopefully you can dump textscan in this case because what you're really after is trying to read your data into Octave... and dlmread does the job for you quite nicely.