0

在 MATLAB 中,如果N = 2这是我需要的行:

M = [V(1)*ones(1,L(1)) V(2)*ones(1,L(2))];

如果N = 3,则该行是:

M = [V(1)*ones(1,L(1)) V(2)*ones(1,L(2)) V(3)*ones(1,L(3))];

我怎么能写一行产生相同的结果N呢?

4

2 回答 2

4

从 R2015a 开始,您可以只使用内置repelem函数:

M = repelem(V,L)

或者如果numel(V)不等于N

M = repelem(V(1:N),L(1:N))

如果您有旧版本的 MATLAB,请考虑一个简单的循环

M = zeros(1, sum(L(1:N)));  %// preallocation
from = 1;
for elem = 1:N
    to = from + L(elem) - 1;
    M(from:to) = v(elem)*ones(1,L(elem));
    from = to + 1;
end
于 2016-04-12T14:20:28.573 回答
2

你可以使用这个:

M = cell2mat(arrayfun(@(v,len) v*ones(1,len), V, L, 'uni', 0));

例子:

>> V=3:5
V =
     3     4     5
>> L=1:3
L =
     1     2     3
>> M=cell2mat(arrayfun(@(v,len) v*ones(1,len), V, L, 'uni', 0))
M =
     3     4     4     5     5     5
于 2016-04-12T14:28:42.120 回答