Question

I want to read COMPLEX data present in a txt file into 1D array in MATLAB. I'm novice in MATLAB. Please help me out.

Excuse me for the ambiguous question. Sincere Apologies..

Actually I have a .txt file containing strings that represents complex numbers(Single line in .txt file represents ) for eg:

1+3i

i

-1-i

.

.

.

So on...

I want to read the same in 1 * N Matrix (where N represents number of complex numbers in .txt file) in MATLAB. How I may do so?

Was it helpful?

Solution

I assume you mean you have a text file with two columns, the real and imaginary parts. In which case, you can do this:

>> type cplx.txt % real and imaginary parts are two columns
1 2
3 4
5 6
>> rawData = dlmread('cplx.txt')

rawData =

     1     2
     3     4
     5     6

>> complexData = complex(rawData(:, 1), rawData(:, 2))

complexData =

   1.0000 + 2.0000i
   3.0000 + 4.0000i
   5.0000 + 6.0000i

EDIT

Ok, with that file format, you should be able to use TEXTSCAN.

>> type cplx2.txt

1+3i
1i
2
4-4i
>> fid = fopen('cplx2.txt', 'rt');
>> x = textscan(fid, '%f');
>> fclose(fid);
>> x{1}

ans =

  1.000000000000000 + 3.000000000000000i
  0.000000000000000 + 1.000000000000000i
  2.000000000000000 + 0.000000000000000i
  4.000000000000000 - 4.000000000000000i

Note that TEXTSCAN can't handle a line that consists of 'i' on its own. Which is a shame.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top