生成重复值序列的向量,每个值都有给定的出现次数

时间:2018-06-27 13:41:14

标签: matlab

我想实现以下功能:

输入:

  1. 值向量

  2. 相同大小的向量,指出每个值(对应索引)在输出向量中应该出现的次数。

输出:

值的向量,按重复序列1by1排列,其中每个值均按所需的出现次数出现。

这些值将继续出现1by1,直到一个值根据需要出现了多次,然后其余的值将继续不显示它。

示例:

输入:

  1. [1,2,3,4]

  2. [3,2,5,1]

输出: [1 2 3 4 1 2 3 1 3 3 3]

想要的解决方案:

我想找到一个简单的解决方案,但不使用任何循环,并且可以对任意长度的输入向量进行模块化。

当前解决方案:

到目前为止,只能通过循环或不愉快的索引来实现。带有循环的解决方案如下:

双循环:

vals_vec=1:4;
occur_vec=[3,2,5,1];
output_vec=zeros(1,sum(occur_vec));
num_of_vals=length(vals_vec);
output_i=1;

while (output_i<=length(output_vec)) % While in length of output vector
    for cur_val_i=1:num_of_vals % Loop over all values
        if(occur_vec(cur_val_i)>0) % If value hasn't reached its occurrence number
            occur_vec(cur_val_i)=occur_vec(cur_val_i)-1;
            output_vec(output_i)=vals_vec(cur_val_i);
            output_i=output_i+1;
        end

    end
end
output_vec

单循环:

vals_vec=1:4;
occur_vec=[3,2,5,1];
output_vec=[];

for cur_num_of_vals=length(vals_vec):-1:1
    [min_val,min_i]=min(occur_vec); % Find lowest occurrence number
    output_vec=[output_vec,repmat(vals_vec,1,min_val)]; % Add vals accordingly
    vals_vec=[vals_vec(1:min_i-1),vals_vec(min_i+1:cur_num_of_vals)]; % Remove the corresponding val
    occur_vec=occur_vec-min_val; % Reduce Occurences from all vals
    occur_vec=[occur_vec(1:min_i-1),occur_vec(min_i+1:cur_num_of_vals)]; % Remove the corresponding occurrence number
end

output_vec

谢谢!

1 个答案:

答案 0 :(得分:5)

您可以通过过度复制输入,然后删除多余的重复来实现。

编辑:这是一个无循环的解决方案:

% Repeat array to max number of possible repetitions
out = repmat( vals, 1, max(reps) ); 
% Implicit expansion (requires R2016b or newer, otherwise use bsxfun) to create
% matrix of reducing repetition count, then remove repeated values
% where this is <= 0, i.e. where there are no repetitions remaining.
out(reshape( reps' - (0:max(reps)-1), 1, [] ) <= 0) = [];

% Pre-R2016b version would be 
% out(reshape( bsxfun(@minus, reps', (0:max(reps)-1)), 1, [] ) <= 0) = [];

原始:需要一个循环,但是在输入值上而不是输出数组上,因此至少是一个短循环...

vals = [1,2,3,4];
reps = [3,2,5,1];
out = repmat( vals, 1, max(reps) ); % repeat array to max number of possible repetitions
for ii = 1:numel(vals)
    % Remove elements which have appeared too many times
    out( out == vals(ii) & (cumsum(out==vals(ii)) > reps(ii)) ) = [];
end