0
votes

I am having difficulty in reading data from a .txt file using Matlab.

I have to create a 200x128 dimension array in Matlab, using the data from the .txt file. This is a repetitive task, and needs automation.

Each row of the .txt file is a complex number of form a+ib, which is of form a[space]b. A sample of my text file :

Link to text file : Click Here

(0)

1.2 2.32222

2.12 3.113

.

.

.

3.2 2.22

(1)

4.4 3.4444

2.33 2.11

2.3 33.3

.

.

.

(2)

.

.

(3)

.

.

(199)

.

.

I have numbers of rows (X), inside the .txt file surrounded by brackets. My final matrix should be of size 200x128. After each (X), there are exactly 128 complex numbers.

2

2 Answers

1
votes

Here is what I would do. First thing, delete the "(0)" types of lines from your text file (could even use a simple shells script for that). This I put into the file called post2.txt.

# First, load the text file into Matlab:
A = load('post2.txt');

# Create the imaginary numbers based on the two columns of data:
vals = A(:,1) + i*A(:,2);

# Then reshape the column of complex numbers into a matrix
mat = reshape(vals, [200,128]);

The mat will be a matrix of 200x128 complex data. Obviously at this point you can put a loop around this to do this multiple times.

Hope that helps.

1
votes

You can read the data in using the following function:

function data = readData(aFilename, m,n)

% if no parameters were passed, use these as defaults:
if ~exist('aFilename', 'var')
    m = 128;
    n = 200;
    aFilename = 'post.txt';
end

% init some stuff:
data= nan(n, m);
formatStr = [repmat('%f', 1, 2*m)];

% Read in the Data:
fid = fopen(aFilename);
for ind = 1:n
    lineID = fgetl(fid);
    dataLine = fscanf(fid, formatStr);
    dataLineComplex = dataLine(1:2:end) + dataLine(2:2:end)*1i;
    data(ind, :) = dataLineComplex;
end
fclose(fid);

(edit) This function can be improved by including the (1) parts in the format string and throwing them out:

function data = readData(aFilename, m,n)

% if no parameters were passed, use these as defaults:
if ~exist('aFilename', 'var')
    m = 128;
    n = 200;
    aFilename = 'post.txt';
end

% init format stuff:
formatStr = ['(%*d)\n' repmat('%f%f\n', 1, m)];

% Read in the Data:
fid = fopen(aFilename);

data = fscanf(fid, formatStr);
data = data(1:2:end) + data(2:2:end)*1i;
data = reshape(data, n,m);

fclose(fid);