Announce

PukiWiki contents have been moved into SONOTS Plugin (20070703)

Matlab File I/O

Table of Contents

read dir

files = dir('.');
for i = 1:length(files)
    filename = files(i).name;
    [path, name, ext, version] = fileparts(filename);
    if strcmp(ext, '.avi')
    % foobar
    end
end

only directories

dirs = dir('.');
dirs = dirs(cell2mat({dirs(:).isdir}));
FILES = {dirs(:).name}

non-directories (files)

dirs = dir('.');
dirs = dirs(cell2mat({dirs(:).isdir}) == 0);
FILES = {dirs(:).name}

read file

Example 1 cvs

a,b,c,d
csvread(filename) % does not work

csvread uses dlmread which supports only numbers.

Example 2 Fixed number of elements in each line.

1 filename
2 filename
[Ns filenames] = textread(filename, '%d %s');

Example 3 Non-fixed number of elements in each line, but only fixed number of elements to be read.

1 filename #ignored #ignored
2 filename #ignored
fid = fopen(filename, 'r');
Ns = []; filenames = [];
for n=1:Inf
    tline = fgetl(fid);
    if ~ischar(tline), break, end
    C = textscan(fid, '%d %s');
    Ns(end+1) = C{1};
    filenames{end+1} = C{2};
end

textscan has N options (repeat scan N times), but we have to know the number of lines to use it, so use an infinite loop.

Example 4 Number of elements to be read is not fixed.

<label> <index1>:<value1> <index2>:<value2> ...
 ...
 ...
fid = fopen(filename, 'r');
X = []; Class = [];
for n=1:Inf
    tline = fgetl(fid);
    if ~ischar(tline), break, end
    [class,remain]=strtok(tline,' ');
    Class(n) = str2num(class);
    while ~strcmp(remain,'')
        [d,remain]=strtok(remain,':');
        [num,remain]=strtok(remain(2:end),' ');
        X(str2num(d),n) = str2num(num);
    end
end

References