Plug4
Plug4

Reputation: 3928

convert multiple .txt to multiple ascii files fast - possible in Matlab?

I have over 120 .txt files (all named like s1.txt, s2.txt, ..., s120.txt) that I need to convert to ASCII extension to use in MATLAB.

my .txt (comma , delimited .txt) files look like the following:
20080102,43.0300,3,9.493,569.567,34174.027,34174027
20080102,43.0600,3,9.498,569.897,34193.801,34193801

In MATLAB I wish to use code similar to the following:

for i = svec; 
   %# where svec = [1 2 13 15] some random number between 1 and 120. 
   eval(['load %mydirectory', eval(['s',int2str(i)]),'.ascii']);
end;

If I am not mistaken I can't use the above command with .txt files and therefore I must use ASCII files.

Since I have a lot of files to convert and they are large in size, is there a quick way to convert all my files via MATLAB, or perhaps there is a great converting software available for Mac on the web? Would anyone have a better suggestion than using the code above?

Upvotes: 0

Views: 996

Answers (3)

Amro
Amro

Reputation: 124543

A slightly cleaner way:

for i=1:120
    fname = fullfile('mydirectory', sprintf('s%d.txt',i));
    X = load(fname, '-ascii');
end

Upvotes: 1

Eitan T
Eitan T

Reputation: 32920

Adding to nrz's answer:

I'm not sure what you want to do exactly, but know that you can open any file in MATLAB, both as text (ASCII) or in binary mode. The latter can be achieved using fread.

As a side note, you also asked for a better suggestion for your code.
Well, what did you try to achieve with the two eval invocations? Why not call the commands directly? Do this instead:

for i = svec
   load (['%mydirectory\s', int2str(i), '.txt'], '-ascii');
end

I also took the liberty to add a backslash that I think you had omitted.

In most cases, you'd be better off without using eval. Check the alternatives...

Upvotes: 1

nrz
nrz

Reputation: 10550

Can you show an example file? Not every text file is valid for load command. If your file is not in a valid format, changing the extension part of filename from .txt to .ascii doesn't help at all. Instead, in that case the data must be either converted to a valid format for load command or, alternatively, loaded into MATLAB by some other means eg. by using fscanf or xlsread. File structure is needed for both ways to solve this.

See also load command in matlab loading blank file.

Upvotes: 1

Related Questions