I want to store each column in struct field, but don't know the data type. How can I accomplish this for any number of columns, without having to use '%s%d%d'?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
theblueeyeswhitedragon
el 6 de Abr. de 2018
Editada: Walter Roberson
el 6 de Abr. de 2018
filename= 'dataFil.txt';
fid = fopen( filename, 'r' ) ;
data = textscan(fid, '%s%d%d', 'delimiter', ',')
fclose(fid);
fieldOne = 'Name';
fieldTwo = 'Num1';
fieldThree ='Num2';
for i = 1:length(data{1})
structOne(i).fieldOne = data{1}(i);
structOne(i).fieldTwo = data{2}(i);
structOne(i).fieldThree = data{3}(i);
end
0 comentarios
Respuesta aceptada
Walter Roberson
el 6 de Abr. de 2018
Editada: Walter Roberson
el 6 de Abr. de 2018
You cannot. If you do not know the types ahead of time, then any type that might be automatically deduced could potentially be incorrect.
For example, if you were to suggest that if the letters a-z or A-Z appear in a field that the field had to be a string then I would point out that you have excluded exponential format with 'e'. If you were to remove 'e' from the banned list, I would point out that you had excluded complex numbers with 'i'. If you were to remove 'i' as well from the list, I would point out that you had excluded complex numbers with 'j' and 'k'. If you removed those from the banned lists, then I would point out that you had excluded fortran-style 'd' double precision numbers. If you were to remove 'd' from the ban too, then I would point out that the first line might or might not be a header line. Then I would point out that sometimes people make mistakes in typing or enter data in the wrong field, so that if you happen to encounter a field with (say) an 'q' in it, that does not necessarily mean the entire column is string, it could be that that one entry is wrong. Oh, and there was a Q format for floating point numbers on Vax. And a G format for IBM FORTRAN II. And an x in a field might be there to indicate hexadecimal. There was also a Z format for floating point, but I do not recall at the moment which system that was for.
And how about if the user accidentally put in a % -- is that a comment marker or is it a percentage sign to be ignored because percent is assumed, or is it an indicator that the number given needs to be divided by 100?
If you want to automatically identify file format, then you need to define strict rules about what will be welcomed, what will be tolerated and corrected under some conditions, and how to determine whether a given entry forces the format for all of the other entries in that column.
... But in the meantime you should probably use readtable() and table2struct() while you try to decide what you are going to do.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Cell Arrays en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!