Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a matrix from a text file in MATLAB?

I have a text file which has 4 columns, each column having 65536 data points. Every element in the row is separated by a comma. For example:

X,Y,Z,AU
4010.0,3210.0,-440.0,0.0
4010.0,3210.0,-420.0,0.0
etc.

So, I have 65536 rows, each row having 4 data values as shown above. I want to convert it into a matrix. I tried importing data from the text file to an excel file, because that way its easy to create a matrix, but I lost more than half the data.

like image 498
Amit Jha Avatar asked Jun 19 '09 03:06

Amit Jha


3 Answers

Have you ever tried using 'importdata'? The parameters you need only file name and delimiter.

>> tmp_data = importdata('your_file.txt',',')

tmp_data = 

          data: [2x4 double]
      textdata: {'X'  'Y'  'Z'  'AU'}
    colheaders: {'X'  'Y'  'Z'  'AU'}


>> tmp_data.data

ans =

        4010        3210        -440           0
        4010        3210        -420           0

>> tmp_data.textdata

ans = 

    'X'    'Y'    'Z'    'AU'
like image 26
Jessada Thutkawkorapin Avatar answered Nov 19 '22 02:11

Jessada Thutkawkorapin


If all the entries in your file are numeric, you can simply use a = load('file.txt'). It should create a 65536x4 matrix a. It is even easier than csvread

like image 157
Dima Avatar answered Nov 19 '22 02:11

Dima


Instead of messing with Excel, you should be able to read the text file directly into MATLAB (using the functions FOPEN, FGETL, FSCANF, and FCLOSE):

fid = fopen('file.dat','rt');  %# Open the data file
headerChars = fgetl(fid);      %# Read the first line of characters
data = fscanf(fid,'%f,%f,%f,%f',[4 inf]).';  %'# Read the data into a
                                              %# 65536-by-4 matrix
fclose(fid);  %# Close the data file
like image 8
gnovice Avatar answered Nov 19 '22 02:11

gnovice