Home > Net >  Python loop for row by column matrix
Python loop for row by column matrix

Time:08-17

I am trying to get a dimension of 103 by 55 of the output c4 below by using a loop in python . However, I could not make the loop work as the output c4 is giving me one single value

my code in pyhton :

  for j in range(np.int64(n)):
      for i in range(np.int64(m)):

           c4 = np.sum(np.log(f))

where n=55 and m=103 and f is a matrix of dimension 1 by 441 . My question is how can I rewrite the line c4 = np.sum(np.log(f)) to incorporate i and j and get a dimension of 103 by 55 in c4 .

This is the working matlab version of the code :

 for j=1:n
    for i=1:m
  

     c4(i,j) = sum(log(f));

     end
  
  end

CodePudding user response:

Note that the MATLAB version itself is wildly inefficient, it computes the sum and log of a 441-element vector m*n times while you need to do that only once. If I were to write it in MATLAB, I'd do c4(1:m,1:n) = sum(log(f)). The equivalent in Python might be as follows:

c4 = np.empty((m, n))
c4.fill(np.sum(np.log(f)))

CodePudding user response:

The equivalent of the matlab code is

c4 = np.empty((m, n))
for j in range(n):
    for i in range(m):
        c4[i, j] = np.sum(np.log(f))

A faster version which leads to the same result is

c4 = np.ones(m, n)) * np.sum(np.log(f))
  • Related