I have been trying to read multiple ASCII files which have file names (23318.asc to 25897.asc). I doesn't seem working. This is what I have so far.

clc,
a= 23318:25897
for k= 1:length(a)
i= 23317+k;
ascFilename = ['3841' num2str(i) '.asc']
content = fscanf ('ascFilename') ;
formatSpec = ['%f%f%*f%f%*f%f', repmat('%*f', 1, 73), '%f%*[^\n]'] ;
data = textscan( content, formatSpec, 'HeaderLines', 12 ) ;
A = data{1};
B= data{2};
C = data{5};
C(C < 0) = NaN; %set negative numbers to 'empty'
length(C)
C
figure(1);
scatter(C,A); %plot first set of data
hold on;
title('Altitude vs Temperature');
ylabel('Temperature');
xlabel('Altitude');
end

1 Comment

What's the error that you're getting? Can you also please format your code by pressing the code {}Code button?

Sign in to comment.

 Accepted Answer

You are not using textscan correctly.
First, you have to use fopen to open the file and create a fileID:
fidin = fopen(ascFilename, 'r'); % Open file for reading
NOTE that because ascFilename has already been created as a string variable, you do not need quotes around it in the fopen statement.
Delete the first line calling textscan. (The line creating content.) It is unnecessary in your code. It’s also wrong and won’t work anyway. It will simply throw an error and stop your code.
Then to read the file, these statements need to be in this order:
formatSpec = ['%f%f%*f%f%*f%f', repmat('%*f', 1, 73), '%f%*[^\n]'] ;
data = textscan( fidin, formatSpec, 'HeaderLines', 12 ) ;
I can’t be certain that this will work because I don’t have you data file to check it with, but it should get you started. If you wrote your formatSpec line correctly, everything you want should be in your data variable

8 Comments

Hey I have another problem. Actually i have almost 10000 files to read. even though the file names are in sequence some files
(13.asc 14.asc) are missing. As an example i have files,
1.asc
2.asc
3.asc
.
.
12.asc
15.asc
16.asc
How can I read this? My last file name is let's say 1000.asc
What should I do now?
If some file names are missing, just after your file name creation statement, check to see if the file exists:
filinfo = which(filename)
if isempty(filinfo)
break
end
If no file exists, the break function will stop further execution of any other statements in your for loop. As I understand it, your loop will then create another file name. If that file exists, the rest of the loop will continue to execute. That should prevent the fopen statement from throwing errors for non-existent files.
But this code does not read the other files. It stops from the missing file.
Thank you very much mate. Works perfectly. you are the best.
As always, my pleasure!
Just noticed ODU. W&L and UVA myself.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!