【问题标题】:MATLAB select variables from the workspace with a specific nameMATLAB 从工作区中选择具有特定名称的变量
【发布时间】:2015-09-05 18:24:53
【问题描述】:

我想选择我的工作区中名称遵循特定模式的所有变量。例如,我想计算工作区中所有变量的平均值,以名称 my_vars 开头。

我尝试了以下代码:

a = who('-regexp','my_vars*')

结果 = 平均值(eval(a))

但是eval 函数不适用于单元格。周围有工作吗?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    who 返回一个由 char 数组(即字符串)组成的元胞数组,每个元素都包含一个变量名。您需要将其转换为包含以逗号分隔的名称列表的字符串。这是一种方法:

    my_vars1 = 1; my_vars2 = 2; my_vars3 = 3;
    names = who('-regexp', 'my_vars*');
    namelist = sprintf('%s,', names{:}); % sprintf reuses the format string if
                                         % there are more inputs than format specifiers 
    namelist(end)=[];                    % strip last comma
    eval(sprintf('mean([%s])', namelist))
    
    ans =
    
         2
    

    【讨论】:

    • 感谢您的回答,它有效!但是,我希望有一种更简单的方法来执行此操作。
    • @mat 简单的方法是使用向量和矩阵来存储数据,而不是离散变量。 my_vars1,my_vars2,my_vars3my_vars(1:3)麻烦多了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多