CeeGee
CeeGee

Reputation: 23

MATLAB: textscan using width delimited txt file

I'm trying to import a width delimited txt file using the textscan function. The file is 80 characters wide, with no delimiter, and the desired resulting 12 columns are different widths of characters. I have tried to do this by specifying the width of the string, (i.e 12 strings, each of a different width of characters that add up to 80) but as soon as there is a space (because certain values are missing) MATLAB interprets this as my delimiter and messes up the format.

data= textscan(fileID, '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s');

I can work around this using Excel but this seems like a bad solution. Is there any way of doing this using MATLAB, maybe a different function than textscan/make textscan forget delimiters and just deal with width of the string?

Upvotes: 0

Views: 436

Answers (2)

craigim
craigim

Reputation: 3914

You need to change the value of the delimiter and white space characters to empty:

format_string = '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s';
C = textscan(fid, format_string, 'delimiter', '', 'whitespace', '');

That way MATLAB will treat each character, including spaces, as valid characters.

Upvotes: 1

GameOfThrows
GameOfThrows

Reputation: 4510

Hmmm, I have experienced the same problem with textscan. Well, here is a long way around it (it is by no means the best solution, but it should work)

fid=fopen('txtfile.txt','rt'); %//load in file
a=fscanf(fid'%c');       %//scan the thing into chars
fclose(fid);

for r = 0:NumberOfRowsInUrData -1    %//Now the loop... Number of rows in your data can also be calculated by size(a,2)/20 
b(r+1,:) = a(1+20*r:20*(r+1)); %// this will correctly index everything 
end

The good thing is that now everything is in the matrix b, you can simply index your chars like string1 = b(:,1:5) and it will output everything in a nice matrix.

The downside ofc is the for loop, which I think you should be able to replace with something like a cellfun or something.

Upvotes: 0

Related Questions