Search code examples
matlabgraphplotmatlab-figureautomatic-properties

MATLAB how to automatically read a number of files


I would like to plot a number of 3D graphs from different data files. For example I am using

fid = fopen('SS   1.dat','r');

to read the first file and then plot a graph. How to set the program to change the name to 'SS 2.dat' automatically? Also for the tenth file the name becomes 'SS 10.dat' which has one space less (i.e.only two space between SS and 10) then the first to ninth files. How to set the program to adjust for that? Thank you.


Solution

  • 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