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

조회 수: 4 (최근 30일)
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
.
.
.

채택된 답변

Bhaskar R
Bhaskar R 2019년 12월 24일
편집: Bhaskar R 2019년 12월 24일
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

추가 답변 (2개)

Walter Roberson
Walter Roberson 2019년 12월 24일
편집: Walter Roberson 2019년 12월 24일
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 2019년 12월 24일
Thank you so much. It worked.

카테고리

Help CenterFile Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by