MATLAB how to automatically read a number of files

爱⌒轻易说出口 提交于 2019-12-02 10:59:45

The following code displays a lazy way to print the names from 1 to 999 that you mentioned:

for ii=1:999
    ns = numel(num2str(ii));
    switch ns
    case 1
        fname = ['ss   ' num2str(ii) '.dat'];
    case 2
        fname = ['ss  ' num2str(ii) '.dat'];
    case 3
        fname = ['ss ' num2str(ii) '.dat'];
    end
end

Another way:

is to use the backslash character in the formatting of the filename as follows:

fstr = 'ss   ';
for ii = 1:999
        ns = numel(num2str(ii));
        for jj = 1:ns-1
            fstr = [fstr '\b'];
        end
        ffstr = sprintf(fstr);
        fname = [ffstr num2str(ii) '.dat'];
        disp(fname);
end

there are many better ways to do this though

Use dir:

filenames = dir('*.dat'); %//gets all files ending on .dat in the pwd
for ii =1:length(filenames)
    fopen(filenames(ii),'r');
    %//Read all your things and store them here
end

The beauty of dir as opposed to the other solutions here is that you can get the contents of the pwd (present working directory) in one single line, regardless of how you called your files. This makes for easier loading of files, since you do not have any hassle with dynamic file names.

prefix = 'SS';

for n = 1:10
    if n == 10
        filename = [prefix ' ' num2str(n) '.dat'];
    else
        filename = [prefix '  ' num2str(n) '.dat'];
    end
    fid = fopen(filename, 'r');
    ...
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!