matlab iterative filenames for saving

你说的曾经没有我的故事 提交于 2019-11-29 15:45:01

For creating a name based of an already existing file, you can use regexp to detect the '_new.(number).mat' and change the string depending on what regexp finds:

original_filename = 'data.string.mat';
im = regexp(original_filename,'_new.\d+.mat')
if isempty(im) % original file, no _new.(j) detected
    newname = [original_filename(1:end-4) '_new.1.mat'];
else
    num = str2double(original_filename(im(end)+5:end-4));
    newname = sprintf('%s_new.%d.mat',original_filename(1:im(end)-1),num+1);
end

This does exactly that, and produces:

    data.string_new.1.mat
    data.string_new.2.mat
    data.string_new.3.mat
    ...

    data.string_new.9.mat
    data.string_new.10.mat
    data.string_new.11.mat

when iterating the above function, starting with 'data.string.mat'

Strings are just vectors of characters. So if you want to iteratively create filenames here's an example of how you would do it:

for j = 1:10,
   filename = ['string_new.' num2str(j) '.mat'];
   disp(filename)
end

The above code will create the following output:

string_new.1.mat
string_new.2.mat
string_new.3.mat
string_new.4.mat
string_new.5.mat
string_new.6.mat
string_new.7.mat
string_new.8.mat
string_new.9.mat
string_new.10.mat

You could also generate all file names in advance using NUM2STR:

>> filenames = cellstr(num2str((1:10)','string_new.%02d.mat'))

filenames = 
    'string_new.01.mat'
    'string_new.02.mat'
    'string_new.03.mat'
    'string_new.04.mat'
    'string_new.05.mat'
    'string_new.06.mat'
    'string_new.07.mat'
    'string_new.08.mat'
    'string_new.09.mat'
    'string_new.10.mat'

Now access the cell array contents as filenames{i} in each iteration

sprintf is very useful for this:

for ii=5:12
    filename = sprintf('data_%02d.mat',ii)
end

this assigns the following strings to filename:

    data_05.mat
    data_06.mat
    data_07.mat
    data_08.mat
    data_09.mat
    data_10.mat
    data_11.mat
    data_12.mat

notice the zero padding. sprintf in general is useful if you want parameterized formatted strings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!