Search code examples
matlabparsingmatlab-figuretext-parsingstring-parsing

Reading data from a Text File into Matlab array


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.


Solution

  • 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.