[英]get matrix of vectors from a vector
I have a vector x = [1,3,5,6,7]
and I want to produce a matrix y
in which rows y(k) = x(k:k+2). 我有一个向量
x = [1,3,5,6,7]
,我想产生一个矩阵y
,其中行y(k)= x(k:k + 2)。 So the resulting matrix in this case would be 因此,在这种情况下得到的矩阵将是
1 3 5
3 5 6
5 6 7
How can I achieve this without using a loop? 如何在不使用循环的情况下实现这一目标? Is there a clever way of doing it with indexing?
有没有一种聪明的方法来做索引?
This is the top non-zero square of a Hankel matrix . 这是Hankel矩阵的顶部非零平方。 Just use
hankel
: 只需使用
hankel
:
>> X = hankel(x)
X =
1 3 5 6 7
3 5 6 7 0
5 6 7 0 0
6 7 0 0 0
7 0 0 0 0
>> X = X(1:3,1:3)
X =
1 3 5
3 5 6
5 6 7
Generalized, hankel
output specified exactly: 指定的广义,
hankel
输出:
w = floor(numel(x)/2);
X = hankel(x(1:end-w),x(w+1:end))
A slightly contrived way using meshgrid
: 使用
meshgrid
一种轻微设计方式:
k = (length(x) + 1) / 2;
[a b] = meshgrid(1:k, 0:k-1);
y = x(a+b);
Or the compact equivalent using bsxfun
或使用
bsxfun
的紧凑等效
y = x(bsxfun(@plus, (1:k)', 0:k-1));
Or a really silly one-liner: 或者是一个非常愚蠢的单行:
y = x(interp2([1 3], [1;3], [1 3; 3 5], 1:3, (1:3)'));
You can do this the following way without direct loop: 您可以通过以下方式执行此操作而无需直接循环:
cell2mat(arrayfun(@(k) x(k:k+2), 1:numel(x) - 2, 'UniformOutput', false)')
ans =
1 3 5
3 5 6
5 6 7
Though, arrayfun
actually loops over elements 1:numel(x) - 2
. 虽然,
arrayfun
实际上循环遍历元素1:numel(x) - 2
。 So its a bit of cheating, i guess. 所以我猜它有点作弊。
Using convolutions: 使用卷积:
n = numel(x)-2; %// x is a row vector with arbitrary length
result = conv2(x,rot90(eye(n)));
result = result(:,n:end-n+1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.