How to load texfile with lots of emptydata values?

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2016-8-14
@Cameron Spooner: please edit your question and upload a sample file by clicking the paperclip icon that you will find above the textbox.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2016-8-14
编辑:Stephen23 2016-8-14
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]

更多回答(0 个)

产品

Community Treasure Hunt

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

Start Hunting!

Translated by