Amit  Jha
Amit Jha

Reputation: 111

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.

Upvotes: 11

Views: 74568

Answers (5)

Jessada Thutkawkorapin
Jessada Thutkawkorapin

Reputation: 1346

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'

Upvotes: 9

Jason S
Jason S

Reputation: 189626

Suggest you familiarize yourself with dlmread and textscan.

dlmread is like csvread but because it can handle any delimiter (tab, space, etc), I tend to use it rather than csvread.

textscan is the real workhorse: lots of options, + it works on open files and is a little more robust to handling "bad" input (e.g. non-numeric data in the file). It can be used like fscanf in gnovice's suggestion, but I think it is faster (don't quote me on that though).

Upvotes: 5

gnovice
gnovice

Reputation: 125854

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

Upvotes: 8

David Johnstone
David Johnstone

Reputation: 24450

The easiest way to do it would be to use MATLAB's csvread function.

There is also this tool which reads CSV files.

You could do it yourself without too much difficulty either: Just loop over each line in the file and split it on commas and put it in your array.

Upvotes: 7

Dima
Dima

Reputation: 39389

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

Upvotes: 24

Related Questions