通过向量中的索引寻址多个范围 [英] Addressing multiple ranges via indices in a vector

查看:68
本文介绍了通过向量中的索引寻址多个范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,可以使用for循环轻松解决此问题.但是,我试图强迫/自学向量矢量思维,以充分利用Matlab的优势.

To begin, this problem is easily solvable with a for-loop. However, I'm trying to force/teach myself to think vector-wise to take advantage of what Matlab does best.

简化,这是问题的说明:

Simplified, here is the problem explanation:

  • 我有一个带有数据的向量.
  • 我有一个2xN的起始/终止索引数组,代表向量中有趣数据的范围.
  • 我想对每个范围进行计算,得出一个数字(N个结果,对应于每个开始/停止范围.)

在代码中,这是我最后想要的伪示例:

In code, here's a pseudoexample of what I'd like to have at the end:

A = 1:10000;
startIndicies = [5 100 1000];
stopIndicies = [10 200 5000];
...
calculatedResults = [func(A(5:10)) func(A(100:200)) func(A(1000:5000))]

A和开始/停止索引数组的长度是可变的.

The length of A, and of the start/stop index array is variable.

就像我说的那样,我可以使用for循环轻松解决此问题.但是,由于可以与大型数据集一起使用,因此我想知道是否有没有for循环的好的解决方案.

Like I said, I can easily solve this with a for loop. However since could be used with a large data set, I'd like to know if there's a good solution without a for loop.

推荐答案

这是一个可能的解决方案,尽管我不会将其称为完全矢量化的解决方案,而是一个一个内衬一个.

Here is one possible solution, although, I won't call it a fully vectorized solution, rather a one liner one.

 out = cellfun(@(i,j) fun(A(i:j)), num2cell(startIndicies), num2cell(stopIndicies) );

或者,如果您打算提供同类输出,

or, if you plan to have homogeneous outputs,

 out = arrayfun(@(i,j) fun(A(i:j)), startIndicies, stopIndicies);

这篇关于通过向量中的索引寻址多个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆