基于向量的每个元素的向量创建-Matlab [英] Vector creation based on each element of a vector - Matlab
问题描述
我想对向量的每个元素应用一个行距函数,并最终创建一个整个向量,有什么方便的方法吗?
I want to apply a linespace function for each element of a vector, and create a whole vector in the end, is there some way convenient to do it?
具体来说,我想使用循环在矩阵 A 没有的情况下通过矩阵 A 创建矩阵 B
A = [1; 2; 3; 4]
B = [1; 1; 2; 1; 2; 3; 1; 2; 3; 4]
Specifically,I want to create matrix B by matrix A without using a loop, where
A = [1; 2; 3; 4]
B = [1; 1; 2; 1; 2; 3; 1; 2; 3; 4]
如您所见,如果向量中的第三个元素为3
,则输出向量 B 中的第三向量"将为[1:1:3].我想要的步骤是固定的,对于任何元素都将是精确的1.
As you can see, if the third element in the vector is 3
, then the "third vector" in the output vector B will be [1:1:3]. The step I desired is fixed and will be exact 1 for any element.
请问有人可以帮我吗?
推荐答案
这里有两种避免循环的方法.
Here are two ways that avoid loops.
-
使用
bsxfun
:这种方法是记忆(或时间)效率低下:
Using
bsxfun
: this approach is memory- (and perhaps time-) inefficient:
t = 1:max(A);
B = nonzeros(bsxfun(@times, t.', bsxfun(@le, t.', t)));
使用 cumsum
:这是内存效率,但更复杂一些:
Using cumsum
: this is memory-efficient, but a little more convoluted:
A = nonzeros(A); % remove zeros, if any
B = ones(1, sum(A)); % initiallize
B(cumsum(A(1:end-1))+1) = 1-A(1:end-1); % write appropriate values...
B = cumsum(B).'; % ... so that the cumulative sum gives the desired output
循环可能是最好的方法:最简单,最清晰.
A loop is probably the best way: simplest and clearest.
这篇关于基于向量的每个元素的向量创建-Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!