How do I import complex numbers from a text file into a matrix in MATLAB?

28 Ansichten (letzte 30 Tage)
I have a text file that contains complex numbers.
My TXT file ("input.txt") has lines formatted as follows:
-1+5i 2+9i 10+3i 8+16i
How do I import these complex numbers into MATLAB as a matrix of doubles?

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 4 Aug. 2023
Bearbeitet: MathWorks Support Team am 7 Aug. 2023
You can import complex numbers into MATLAB as a matrix of doubles in various ways, which are outlined below.
1. Use the "readmatrix" function:
complex_numbers = readmatrix("input.txt", "OutputType","double");
2. Use the "textscan" function:
fileID = fopen("input.txt");
complex_numbers = cell2mat(textscan(fileID, "%f"));
3. Use the "readtable" function
complex_numbers_as_table = readtable("input.txt");
complex_numbers = table2array(complex_numbers_as_table);
4. Use the "readlines" function:
raw_data = readlines("input.txt")
complex_numbers_as_strings = split(raw_data, " ")
complex_numbers = [];
for i=1:length(complex_numbers_as_strings)
complex_number_components = split(complex_numbers_as_strings(i), {'+','i'});
real_part = double(complex_number_components(1))
imaginery_part = double(complex_number_components(2))
complex_numbers = [complex_numbers complex(real_part, imaginery_part)]
end

Weitere Antworten (0)

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by