向量化冒号(:)的概念-MATLAB中两个向量之间的值 [英] Vectorizing the Notion of Colon (:) - values between two vectors in MATLAB
问题描述
我有两个向量,idx1
和idx2
,我想获得它们之间的值.如果idx1
和idx2
是数字而不是向量,我可以通过以下方式做到这一点:
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
但是在我的情况下,idx1
和idx2
是可变长度的向量.例如,对于length = 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屋!