Read a file contains hexdecimal complex numbers, and convert decimal complex numbers

4 views (last 30 days)
Hi All,
I want to read a file contains hexdecimal complex numbers, and convert decimal complex numbers.
Each line has one hexdecimal complex number. I want to read all lines, and conver the decimal complex number (real and imag parts) and store them in an array. I tried textread, textscan, and so on. I also tried to read them as "str" and split them into two part and convert and combine later. However, all of my approaches failed actually. Please help!
<real_imag.txt>
fffd+0000*i
0016+0000*i
0000+ffff*i
.
.
.

Accepted Answer

Bhaskar R
Bhaskar R on 24 Dec 2019
Edited: Bhaskar R on 24 Dec 2019
data = fileread('real_imag.txt'); % read data in all char
data_hex = regexp(data, '[\d\w]*', 'match'); % divide all into three parts [real, imag, i] with reguler exp
data_dec = hex2dec(data_hex(1:3:end))+hex2dec(data_hex(2:3:end))*i; % data in decimal

More Answers (2)

Walter Roberson
Walter Roberson on 24 Dec 2019
Edited: Walter Roberson on 24 Dec 2019
There are three possible reasonable interpretations:
fid = fopen('real_imag.txt', 'rt');
data_cell = textscan(fid, '%4x%c%4x');
fclose(fid);
csign = (data_cell{2}=='+')*2-1;
%case where components are unsigned 16 bit and the complex sign is guaranteed positive:
vals_uint16 = complex(uint16(data_cell{1}), uint16(data_cell{3}));
%case where components are unsigned 16 bit but the complex sign is not guaranteed positive. negative of an unsigned 16 bit needs more than 16 bits
vals_int32 = complex(int32(data_cell{1}), int32(csign) .* int32(data_cell{3}));
%case where components are signed 16 bit and the complex sign is positive just as a notation placeholder
vals_int16 = complex(typecast(uint16(data_cell{1}),'int16'), typecast(uint16(data_cell{3}),'int16'));

Jaeyoung
Jaeyoung on 24 Dec 2019
Thank you so much. It worked.

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!