How do I import complex numbers from a text file into a matrix in MATLAB?
25 views (last 30 days)
Show older comments
MathWorks Support Team
on 3 Aug 2023
Edited: MathWorks Support Team
on 7 Aug 2023
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?
Accepted Answer
MathWorks Support Team
on 4 Aug 2023
Edited: MathWorks Support Team
on 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Text Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!