how do i read just the header in a csv file and write them into a file
38 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Adam Jurhs
le 5 Juil 2022
Modifié(e) : Adam Jurhs
le 7 Juil 2022
hi guys,
i have a csv file that i'd like to get a listing of all the headers, transposed into one column, and then write them out to a new file. so far what i've done is:
str = fileread('filename.csv')
index = strfind(str, '1');
header = str(1:(index-1));
and that gives me a character array with a single a row of all the fields in header seperated by commas, see below
header='field1,field2,field3,field4,field5'
what i need is a new file with the field names written as a column
field1
field2
field3
field4
field5
thanks for whatever help you can give!
Todd
0 commentaires
Réponse acceptée
Star Strider
le 5 Juil 2022
One approach —
header='field1,field2,field3,field4,field5'
headerstring = string(strsplit(header,',')).'
.
7 commentaires
Star Strider
le 5 Juil 2022
Thank you!
file1 = ["field1"
"field2"
"field3"
"field4"
"field5"];
file2 = ["field1"
"apples"
"bannans"
"field5"
"oranges"];
Lv = ismember(file1, file2) % Logical Vector
Result = file1(Lv)
... as desired!
You can also use ‘Lv’ here as the row (first) index to refer to multiple columns of the matrix, something like:
newDataExtract = newData(Lv,:)
if necessary.
.
Plus de réponses (2)
Adam Jurhs
le 6 Juil 2022
1 commentaire
Star Strider
le 6 Juil 2022
The ‘Lv’ vector indexes into the first argument of ismember. In the situation you describe, the first argument should be the longest vector, since that would correspond to the ‘Lv’ output.
I initially chose ismember because it appeared to be appropriate for the situation you describe. An alternative to experiment with, that may be closer to what you want, is the intersect function.
A = randi(9, 5, 1)
B = randi(9, 7, 1)
[C,ia,ib] = intersect(A,B)
Aia = A(ia)
Bib = B(ib)
The disadvantage of using intersect however is that it returns only the index of the first occurrence in each vector. If you expect only one match in each vector, that works. If there could be more than one match, and you want all of them, it won’t.
.
Adam Jurhs
le 7 Juil 2022
Modifié(e) : Adam Jurhs
le 7 Juil 2022
3 commentaires
Star Strider
le 7 Juil 2022
As always, my pleasure!
You just did! (Also by accepting my answer, for which I thank you!)
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!