Reading data from a text file, comma delimited

Hi
I want to read data from a textfile, any help will be nice.
The actual data looks like this.
A B
1, 2
3, 4
5, 6
7, 8
But in the text file the data looks like this: 1, 23, 45, 67, 8
how do i read it so that i store 1 3 5 7 in A without the commas and 2 4 6 8 in B without commas.
Thanks.

Réponses (1)

Adam Danz
Adam Danz le 17 Août 2018
Modifié(e) : Adam Danz le 17 Août 2018
readtable() seems to work with your example data.
m = readtable('test.txt')
m =
4×2 table
A B
_ _
1 2
3 4
5 6
7 8
m.A is your first column.
m.B is your second column.
If the first row of your data, "A B", really isn't separated by a comma, you'll lose those variables names in your table (m.Var1 instead of m.A). If they do have a comma, your table will contain the variable names. I put a comma in your example to produce my outputs.

8 commentaires

EEEmatlab
EEEmatlab le 17 Août 2018
Yes, thanks this works. but how would i do this manually, using fopen and scanning.
Adam Danz
Adam Danz le 17 Août 2018
readtable() doesn't require fopen(). I'm not sure what you're asking.
EEEmatlab
EEEmatlab le 17 Août 2018
readtable is a built in function, i want to do this by opening the file and then using textscan or fscan, but i am not sure how to.
Adam Danz
Adam Danz le 17 Août 2018
Both textscan and fscanf are built-in functions as well. If readtable() works with your data, what's your motivation to use a different method?
I unfortunately won't have access to matlab for a while so I can't try other methods at this time.
Image Analyst
Image Analyst le 17 Août 2018
Because you don't want to use a high level function that does what you want perfectly well, but want to use a more primitive, low level function tells me that this must be your homework.
So please read this link.
Then look up the help for fopen(), fgetl(), sscanf(), and fclose(). It's rather straightforward and a smart person like yourself will have no trouble with them.
fileID = fopen('Data001a.txt')
i=1;
while 1
tline = fgetl(fileID);
if ~ischar(tline), break, end
disp(tline)
text{i} = tline
data{i} = sscanf(text{i},'%f, %f');
real(i) = data{i}(1)
img(i) = data{i}(2)
i = i+1;
end
fclose(fileID)
I got this code A is real, B is img. Is this the best way to do it or are there better solutions?
EEEmatlab
EEEmatlab le 18 Août 2018
also i noticed in some places you have to use {} and in others () why is this?
Adam Danz
Adam Danz le 18 Août 2018
Is this the best way to do what?
What do you mean "A is real, B is img"?
This seems far from your original question so maybe it would be better to post a new question for fresh eyes.
Curly brackets { } are used to index cell arrays while parentheses ( ) can be used to index matrices.

Connectez-vous pour commenter.

Question posée :

le 17 Août 2018

Commenté :

le 18 Août 2018

Community Treasure Hunt

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

Start Hunting!

Translated by