回 帖 发 新 帖 刷新版面

主题:大家帮我看看这段程序--将数组中的重复元素替换成不重复的数字

要将ss中的重复元素替换成不重复的数字

ss=[2 4 6 2 5 1 3 9 2 10]
     temp=zeros(1,10)     %生成元素为0的矩阵
     for j=1:9   
         for k=j+1:10
           pos1=ss(j)
           pos2=ss(k)
             temp(j)=pos1
        %变异位置不相同
        while pos1==pos2      
            pos2=unidrnd(10)      %随机生成1个小于10的数字
            if   ismember(pos2,temp)==0          %如果pos2在temp中的话,返回1,否则,返回0
                
                ss(k)=pos2  
            
            end
          end
        end 
     end

回复列表 (共1个回复)

沙发

clc;
ss=[2 4 6 2 5 1 3 9 2 10];
ss_size=size(ss);
temp=zeros(1,ss_size(2));     %生成元素为0的矩阵
for j=1:ss_size(2)   
      pos1=ss(j);
       temp =ss;
        temp(j) = 0;
        %变异位置不相同
   while ismember(pos1,temp)==1       
            pos1=unidrnd(ss_size(2)) ;     %随机生成1个小于10的数字
            ss(j) = pos1;
   end
end

我来回复

您尚未登录,请登录后再回复。点此登录或注册