MATLAB Answers

Creating a txt file with different types of data stored in each column?

1 view (last 30 days)
Jonathan Marchetto
Jonathan Marchetto on 15 Feb 2018
Commented: Star Strider on 16 Feb 2018
I am trying to create a .txt file with the following data in this format.
e 5.4 300+2i
f 3.3 3+200i
c 2.2 9.9+210i
f 1.1 2.290+0.1i
with e,f,c,f beign strings, and the last numbers being complex numbers.
I'm not sure what the best way to go about this. Should I create a cell array and then use fprintf to create a .txt file?

  0 Comments

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 15 Feb 2018
If you have R2013b or later, create the cell array, then use the cell2table function to create a table, then use writetable to write the file.
Example
C = {'e' 5.4+300+2i
'f' 3.3+3+200i
'c' 2.2+9.9+210i
'f' 1.1+2.290+0.1i};
T = cell2table(C)
T =
4×2 table
C1 C2
___ __________
'e' 305.4+2i
'f' 6.3+200i
'c' 12.1+210i
'f' 3.39+0.1i
Then write to the file.

  5 Comments

Show 2 older comments
Jonathan Marchetto
Jonathan Marchetto on 16 Feb 2018
Hey Star Strider.
I've actually tried that format spec, but for some reason I am getting C = 1x3 cell array. The first cell has a 5x1 array with all of the values in it, the other two have NaN and NaN.
Here is my code:
%Q1
C = {'e' 5.4 300+2i
'f' 3.3 3+200i
'c' 2.2 9.9+210i
'f' 1.1 2.290+0.1i};
CharNumber = cell2table(C)
writetable(CharNumber)
%Q2
fileid = fopen('CharNumber.txt', 'r')
C = textscan(fileid,'%s%f%f')
celldisp(C)
fclose(fileid)
-----
And here is what I'm getting (attached as file)
Star Strider
Star Strider on 16 Feb 2018
I did not realise this is a homework assignment. My objective was to use writetable so you can use readtable to read it again. The writetable function defaults to a comma-delimited text file, so in your textscan call, specify the delimiter to be a comma. That should work.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by