How to load texfile with lots of emptydata values?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Cameron Spooner
el 14 de Ag. de 2016
I have a tab delineated textfile which is formatted as below;
1 2 3 4 5 6 7 8
1 * * * 5 * * *
1 * * * * * * *
1 * 3 * * * * *
1 * * * * * * 8
The first row of data is headers which I am not loading. I have used a * above to represent an emptydata value in the text file. The first column has continuous values but the rest are mostly made up of empty values.
I have tried using textscan to load the data but it only seems to load the first column and ignore the others even though I have tried to set it up to deal with empty values. The code I am using for this is;
indata = textscan(fid, '%s%s%s%s%s%s%s%s', 'Delimiter', '\t', 'HeaderLines',1, 'EmptyValue',0);
fclose(fid);
data = indata{1};
The desired output I am looking for is;
1 2 3 4 5 6 7 8
1 0 0 0 5 0 0 0
1 0 0 0 0 0 0 0
1 0 3 0 0 0 0 0
1 0 0 0 0 0 0 8
What do I need to change to the code above to get it to do this?
2 comentarios
Stephen23
el 14 de Ag. de 2016
@Cameron Spooner: please edit your question and upload a sample file by clicking the paperclip icon that you will find above the textbox.
Respuesta aceptada
Stephen23
el 14 de Ag. de 2016
Editada: Stephen23
el 14 de Ag. de 2016
This reads the file (attached):
opt = {'Delimiter','\t', 'HeaderLines',1};
fmt = repmat('%s',1,8);
fid = fopen('Rockfalls.txt');
C = textscan(fid,fmt,opt{:});
fclose(fid);
C = horzcat(C{:});
And (part of) the output:
>> C(1:4,:)
ans =
[1x20 char] '' '' '' '' 'X' '' ''
[1x20 char] '' '' '' '' '' '' ''
[1x20 char] '' '' '' '' '' '' ''
[1x20 char] '' 'X' '' '' '' '' ''
When you read the textscan documentation it clearly says that the option 'EmptyValue' only applies to numeric fields: "Value to return for empty numeric fields in delimited files", so there is no point is using this with your string data.
If you want to replace the empty cells of the cell array, then try this:
C(cellfun('isempty',C)) = {0};
to give:
>> C(1:4,:)
ans =
[1x20 char] [0] [0] [0] [0] 'X' [0] [0]
[1x20 char] [0] [0] [0] [0] [0] [0] [0]
[1x20 char] [0] [0] [0] [0] [0] [0] [0]
[1x20 char] [0] 'X' [0] [0] [0] [0] [0]
1 comentario
Más respuestas (0)
Ver también
Categorías
Más información sobre Text Files 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!