为每个元素添加1而不是零,matlab

时间:2014-04-20 20:52:43

标签: matlab vector

我存储的向量RVE,我只想为每个不为零的元素添加一个。因此,每个非零元素都将保留,并且矩阵a 0中不是1的每个数字都将添加到其中。

例如:

[1 0 0 0 0 0 0 0] -> [2 0 0 0 0 0 0 0]

[5 3 1 0 0 0 0 0] -> [6 4 2 0 0 0 0 0]

代码:

n=100;
primlist=2; % starting the prime number list


for numba=1:n;
   if mod(2+numba,primlist)~=0
      primlist=[primlist;2+numba]; %generating the prime number list
   end
end


for numbas=2:n
    prims=zeros(size(primlist));
    pprims=zeros(size(primlist));
    pow=prims;
    for k=1:10
        for i=1:length(primlist) % identifying each primes in the primlist
            if mod(numbas,primlist(i).^k)==0
                prims(i)=primlist(i); % sum of all the powers of prims, such that prims divide numbas
                pow(i)=k; % collecting the exponents of primes
            end

            if primlist(i)<=numbas
               pprims(i)=primlist(i);
            end
        end


    PPRIMS=pprims' % primes less than or equal to numbas   
    PRIMS=prims'; % primes that divide numbas
    POW=pow'; % highest prower of primes that divide numbas

    PPV(numbas,:)=PRIMS; % saving prims
    PVE(numbas,:)=POW; % Saving Pows
    PLV(numbas.:)=PPRIMS % saving PPRIMS
    numbas;


    RVE=cumsum(PVE); % the cummulative sum of the exponents of PVE
    %RVE1(numbas,:)=RVE

      for x=1:26

        RVE(numbas,x);
        if x~=0
            RVE1=RVE(numbas,x+1)
        end
      end

%sigmafac=(prod(PPV.^(RVE(numbas)+1)-1))/((prod(PPV-1))) 
end



end                

4 个答案:

答案 0 :(得分:2)

RVE = RVE + (RVE ~= 0)

上面的条件部分将返回1的矩阵/向量(元素不为0)和0(元素为0)。将此结果添加回原始Matrix。

答案 1 :(得分:1)

逻辑索引方法:

RVE=[5 3 1 0 0 0 0 0];
RVE(RVE~=0)=RVE(RVE~=0)+1;

结果:

RVE =

     6     4     2     0     0     0     0     0

答案 2 :(得分:1)

您可以这样做:

x = [1 2 3 0 0 0 0 0];
y = x+(x~=0);

答案 3 :(得分:1)

RVE(RVE~=0)选择每个非零元素。添加1次使用

RVE(RVE~=0)=RVE(RVE~=0)+1