Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
例如,A = [19 20 21 22 23 24 25]; B = [2 0 3 0 0 0 2];
A = [19 20 21 22 23 24 25];
B = [2 0 3 0 0 0 2];
我们如何获得一个新数组,将 B 中的每个值相应地重复 X 次?
例如,这里的答案是:[19 19 21 21 21 25 25]。
[19 19 21 21 21 25 25]
请注意,我只允许与呼叫for结合使用循环。repmat
for
repmat
如果只允许使用repmat和for循环,则可以执行以下操作:
S = []; for idx = 1 : length(B) S = [S repmat(A(idx), 1, B(idx))]; end
S最初是一个空白数组,然后对于与 in 一样多的值B(或者A因为它们的长度都相等),只需将S其中的每个值A与B. S将包含输出。
S
B
A
通过运行上面的示例,我得到:
S = 19 19 21 21 21 25 25
但是,我强烈建议您使用更多的矢量化方法。我会把它留给你作为练习。
祝你好运!