【问题标题】:Selecting elements of a vector based on two vectors of starting and ending positions matlab基于开始和结束位置的两个向量matlab选择向量的元素
【发布时间】:2012-07-23 09:43:28
【问题描述】:

感谢您对 matlab 中以下问题的帮助: 我有一个向量,我想根据以下两个部分的开始和结束索引向量来选择它的一部分:

aa = [1   22  41  64  83   105  127  147  170  190  212  233]
bb = [21  40  63  82  104  126  146  169  189  211  232  252]

基本上我想在V(1:21)V(22:40)、...V(233:252) 上执行一些功能。 我试过V(aa:bb)V(aa(t):bb(t)) 其中t = 1:12 但我只得到V(1:21),可能是因为V(22:40) 有19 个元素,而V(1:21) 有22 个元素。

有没有一种快速的编程方法?

【问题讨论】:

  • 你要应用什么功能?

标签: matlab vectorization


【解决方案1】:

将您的选择放入一个单元格数组中,并将您的函数应用于每个单元格:

aa = [1   22  41  64  83   105  127  147  170  190  212  233]
bb = [21  40  63  82  104  126  146  169  189  211  232  252]
V = rand(252,1); % some sample data

selV = arrayfun(@(t) V(aa(t):bb(t)), 1:12,'uniformoutput',false);
result = cellfun(@yourfunction,selV)
% or
result = cellfun(@(selVi) yourfunction(selVi), selV);

如果您要应用的函数对每个向量输入都有标量输出,这应该给您一个 1x12 数组。如果函数提供向量输出,则必须包含 uniformoutput 参数:

result = cellfun(@(selVi) yourfunction(selVi), selV,'uniformoutput',false);

它为您提供一个 1x12 元胞数组。

【讨论】:

    【解决方案2】:

    如果你想以高度浓缩的形式运行它,你可以写(两行,为了清楚起见)

    aa = [1   22  41  64  83   105  127  147  170  190  212  233]
    bb = [21  40  63  82  104  126  146  169  189  211  232  252]
    V = rand(252,1); % some sample data borrowed from @Gunther
    
    %# create an anonymous function that accepts start/end of range as input
    myFunctionHandle = @(low,high)someFunction(V(low:high));
    
    %# calculate result
    %# if "someFunction" returns a scalar, you can drop the 'Uni',false part
    %# from arrayfun
    result = arrayfun(myFunctionHandle(low,high),aa,bb,'uni',false)
    

    请注意,目前这可能比显式循环运行得更慢,但 arrayfun 在未来的版本中可能会是多线程的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2017-07-14
      相关资源
      最近更新 更多