【问题标题】:matrix dimensions wont agree when elements match/matlab元素匹配/matlab 时矩阵尺寸不一致
【发布时间】:2014-04-21 18:57:52
【问题描述】:

我在代码的最后计算时遇到问题,最后一部分,其中 log 是自然对数,我需要 RD=facs.*log(log(facs)) 来划分 sigmafac,或者 robin=sigmafac ./RD.我的 RD 从 1 到 100,我的 sigmafac 也是如此。为什么会出现矩阵维度不匹配?

我希望RD的对应数(numbas)除以sigmafac的对应数,都具有相同的维度,所以我看不出问题出在哪里。我意识到 RD(1)=-inf,这是导致问题的原因吗?以及如何解决?

代码:

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

fac=1; %initializing the factorials
RD=0;

for numbas=2:n

    %preallocating vectors for later use
    prims=zeros(size(primlist));
    pprims=zeros(size(primlist));
    pow=prims;

    for i=1:length(primlist) % identifying each primes in the primlist
        for k=1:10
            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
        end

    if primlist(i)<=numbas
       pprims(i)=primlist(i); % primes less than or equal to numbas
    end

    end 


   % converting column vectors to row vector  
   PPRIMS=pprims';
   PRIMS=prims';
   POW=pow';


   %Creating the vectors
   PLN(numbas,:)=PPRIMS; % vector of primes less than or equal to number

   PPV(numbas,:)=PRIMS; % prime divisor vector

   PVE(numbas,:)=POW; % highest power of each primes for every number

   RVE=cumsum(PVE); % the cummulative sum of the exponents

   RVE(RVE~=0)=RVE(RVE~=0)+1; %selects each non zero element then add 1


   %factorial
   fac=fac*numbas;
   facs(numbas)=fac; %storing the factorials

   if facs==1
    RD==1; % log(log(facs1))) does not exist
   else RD=facs.*log(log(facs));
   end




end                


% setting up sum of divisor vector
NV=PLN.^RVE-1; % numerator part of sum of divisors vector
DV=PLN-1; % denominator part of sum of divisors

NV(NV==0)=1; % getting rid of 0 for elementwise product
DV(DV==-1)=1; % getting rid of -1 for elementwise product


sigmafac=prod(NV,2)./prod(DV,2); %sum of divisors


robin=(sigmafac)./(RD)

【问题讨论】:

    标签: matlab


    【解决方案1】:

    每当你遇到这样的错误,你的第一个检查应该是测试

    size(sigmafac)
    size(RD)
    

    在这种情况下,你会得到

    ans =
       100     1
    ans =
         1   100
    

    所以它们的大小不同。您需要对其中一个进行转置,然后您的分区才能正常工作。

    【讨论】:

      【解决方案2】:

      您的 sigmafac 是 100x1,但您的 RD 是 1x100,这会产生错误。如果你想让它工作,只需改变

      robin=(sigmafac)./(RD)
      

      robin=(sigmafac)'./(RD)
      

      这将使 sigmafac 成为 1x100(转置),然后您的向量将具有相同的维度,您将能够进行除法。

      【讨论】:

      • 我不知道该感谢你多少,我真的很感激!谢谢大哥!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多