【问题标题】:What's the easiest way to generate multiple similar scripts or files?生成多个类似脚本或文件的最简单方法是什么?
【发布时间】:2014-01-29 16:05:23
【问题描述】:

我一直将多个 matlab 脚本作为数组作业提交到集群,这很有效。但我一直在手动生成每个脚本!比如x = 1:1000,我想改一下:

文件名 = foo_x.m

和mscript中的参数

a = x;
b = 'x_1';
c = 'x_2';

即任务是生成多个完全相同的文件,除了它们的 x 值。 x 出现在脚本和文件名中。

我对 python、sed 和 vim 有少量经验。关于解决此类任务的最佳方法的任何建议,或那里的任何教程?

【问题讨论】:

  • 这听起来很奇怪。您确定在您的集群软件中无法提交具有可变参数的 MATLAB 函数吗?或者从 MATLAB 脚本中提取作业编号并使用它来选择 x?或者访问和修改具有 x 运行值的共享文件?
  • 啊哈是的,这些绝对是很棒的建议,会让我的目录更好看!我这样做的方式是我从通过 qsub 提交每个(令人尴尬的并行)作业到在数组作业中一起提交它们的自然进展。

标签: python matlab vim sed


【解决方案1】:

在 Matlab 中使用diary 的快速解决方案:

for x = 1:1000
    diary(['foo_' num2str(x) '.m' ])
    disp(['a = ' num2str(x) ';'])
    disp(['b = ''' num2str(x) '_1'';'])
    disp(['c = ''' num2str(x) '_2'';'])
    diary off
    disp(' ')
end

如果您需要“foo_0001.m”形式的文件名(即在左边用零填充数字),请将循环中的第一行替换为

    diary(['foo_' num2str(x,'%.4d') '.m' ])

【讨论】:

  • 喜欢这个谢谢。没想到matlab有这样的能力
  • 哦,但是您必须在文件中的每一行周围加上disp('')
  • 是的。 disp 在命令窗口中显示其输入字符串; diary 将命令窗口中显示的内容保存到磁盘
【解决方案2】:

Python 解决方案

使用str.format

在以下代码中template 包含{0}。将其视为占位符。使用str.format,您可以用str.format 的第一个参数替换它。

template = '''
a = {0};
b = '{0}_1';
b = '{0}_2';
'''

for x in range(1, 1000+1): # loop from 1 to 1000
    with open('foo_{}.m'.format(x), 'w') as f: # Open file ("w"rite mode)
        f.write(template.format(x)) # render the template string
                                    #  replacing placeholder (`{0}`)

如果您希望文件名看起来像 foo_0012.m 而不是 foo_12.m,请将 foo_{}.m 替换为 foo_{:04}.m

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-06
    • 2011-03-06
    • 2010-10-18
    • 2010-09-23
    • 1970-01-01
    • 2011-05-12
    • 2023-01-12
    • 2014-05-16
    相关资源
    最近更新 更多