向量化冒号 (:) 的概念 - MATLAB 中两个向量之间的值 [英] Vectorizing the Notion of Colon (:) - values between two vectors in MATLAB

查看:37
本文介绍了向量化冒号 (:) 的概念 - MATLAB 中两个向量之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量,idx1idx2,我想获取它们之间的值.如果 idx1idx2 是数字而不是向量,我可以这样做:

I have two vectors, idx1 and idx2, and I want to obtain the values between them. If idx1 and idx2 were numbers and not vectors, I could do that the following way:

idx1=1;
idx2=5;
values=idx1:idx2 

% Result
 % values =
 % 
 %    1     2     3     4     5

但在我的例子中,idx1idx2 是可变长度的向量.例如,对于长度=2:

But in my case, idx1 and idx2 are vectors of variable length. For example, for length=2:

idx1=[5,9];
idx2=[9 11];

我可以使用冒号运算符直接获取两者之间的值吗?这是,类似于以下内容:

Can I use the colon operator to directly obtain the values in between? This is, something similar to the following:

values = [5     6     7     8     9     9    10    11]

我知道我可以做 idx1(1):idx2(1)idx1(2):idx2(2),也就是说,提取每个的值单独列,所以如果没有其他解决方案,我可以用 for 循环来做到这一点,但也许 Matlab 可以更轻松地做到这一点.

I know I can do idx1(1):idx2(1) and idx1(2):idx2(2), this is, extract the values for each column separately, so if there is no other solution, I can do this with a for-loop, but maybe Matlab can do this more easily.

推荐答案

您的示例输出不合法.矩阵不能有不同长度的行.您可以做的是使用 arrayfun 创建一个元胞数组:

Your sample output is not legal. A matrix cannot have rows of different length. What you can do is create a cell array using arrayfun:

values = arrayfun(@colon, idx1, idx2, 'Uniform', false)

要将生成的元胞数组转换为向量,您可以使用 cell2mat:

To convert the resulting cell array into a vector, you can use cell2mat:

values = cell2mat(values);

或者,如果生成的元胞数组中的所有向量都具有相同的长度,则可以构造如下输出矩阵:

Alternatively, if all vectors in the resulting cell array have the same length, you can construct an output matrix as follows:

values = vertcat(values{:});

这篇关于向量化冒号 (:) 的概念 - MATLAB 中两个向量之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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