【问题标题】:Transparency - replace EVAL in matlab透明度 - 在 matlab 中替换 EVAL
【发布时间】:2016-09-27 20:34:18
【问题描述】:

我有以下代码在 matlab 上进行一些排序,但依赖于 eval。这是一组更大的代码的一部分,我已经简化了它以便能够把它放在这里。基本上,我正在寻找一种摆脱函数 eval 的简单方法,以便我可以在代码的前面使用 parfor 语句。

t = 1;
N = 1500;
BM = rand(N,1);
P1 = rand(N,12);
nport = 10;
tSpan            = t : t + 11;
pointer = round([1; N*.10; N*.20; N*.30; N*.40;N*.50; N*.60; N*.70; N*.80; N*.90; N]);  % pointers used in sorting
IndStru  = struct('idp1', [], 'idp2', [], 'idp3', [], 'idp4', [], 'idp5',[],'idp6', [], 'idp7', [], 'idp8', [], 'idp9', [], 'idp10',[]);


[ssize, sInd] = sort(BM);     clear ssize
ids1    = sInd(pointer(1)     : pointer(2));
ids2    = sInd(pointer(2) + 1 : pointer(3));
ids3    = sInd(pointer(3) + 1 : pointer(4));
ids4    = sInd(pointer(4) + 1 : pointer(5));
ids5    = sInd(pointer(5) + 1 : pointer(6));     
ids6    = sInd(pointer(6) + 1 : pointer(7));
ids7    = sInd(pointer(7) + 1 : pointer(8));
ids8    = sInd(pointer(8) + 1 : pointer(9));
ids9    = sInd(pointer(9) + 1 : pointer(10));
ids10    = sInd(pointer(10) + 1 : pointer(11));     clear sInd

for i = 1 : nport
            eval(['IndStru.idp' num2str(i) '=ids' num2str(i) ';' ]);
            eval(['p10(' num2str(i) ',' num2str(tSpan(1)) ':' num2str(tSpan(12)) ') = sum(P1(IndStru.idp' num2str(i) ', tSpan))']);

end

【问题讨论】:

  • 您的示例不起作用,特别是第 24 行,加上缺少的 for。至于第一个eval,看Generate Field Names from Variables,第二个就可以拼出来,不用字符串。
  • 谢谢。转换此 MWE 的代码时出现拼写错误。现在应该没问题了。我会看看你发布的链接。
  • 实际上,我认为您在这方面走错路了?带有编号字段的结构看起来很奇怪。你想解决什么问题。
  • 我有一个向量 BM,我想把它分成 10 个部分(nport)。一旦完成,我想使用 P1 计算一些东西,给定 BM 的 10 个部分。在我的实际代码中,for 循环的最后一行稍微复杂一些。
  • 那么结构体IndStru只是为了索引?

标签: matlab eval transparency parfor


【解决方案1】:

没有机会详细尝试,但这里是您问题的通用答案:

您目前在结构(或字段?)的名称中放置了一个索引

与其这样做,不如简单地保持名称固定并添加维度。

因此,不要使用myvar1 之类的变量,而是使用struct 之类的myvar(1)

完成此更改后,无需 eval 即可轻松访问所有数据。

【讨论】:

    【解决方案2】:

    据我所知,以下应该是等价的

    t = 1;
    N = 1500;
    BM = rand(N,1);
    P1 = rand(N,12);
    nport = 10;
    tSpan = t : t + 11;
    
    [~, sInd] = sort(BM);
    ids = zeros(N/nport, nport);
    for i = 1:nport   
       ids(:,i) = sInd(((i-1)*N/nport +1):i*N/nport);
    end
    
    p10 = zeros(nport, 12);
    for i = 1 : nport
       p10(i, tSpan) = sum(P1(ids(:,i), tSpan), 1);           
    end
    

    我没有使用结构来存储索引,而是生成了一个索引矩阵ids 以在 P1 中使用。

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 2020-07-12
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      相关资源
      最近更新 更多