0

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
7
  • This has nothing to do with MATLAB. Please don't spam tags. Commented Aug 16, 2022 at 14:34
  • It's not clear what you want to do. I assume you don't want c4 to have the same result for every i and j, which is inevitable at the moment because you are not using i or j here c4 = np.sum(np.log(f)). Do you want to apply the log and sum for each row in f ? Commented Aug 16, 2022 at 14:37
  • I want to have a dimension of 103 by 55 after applying log and sum in f by looping them . However, the dimension of f is different and I don't want the dimension of f in c4 Commented Aug 16, 2022 at 14:40
  • How are you going to get dimensions of 103 by 55 from a matrix of shape 1 by 441? 441/103=4.28 and 441/55=8.018, it's not logical. Commented Aug 16, 2022 at 14:43
  • 1
    Based on the provided code you can do c4[:n,:m] = np.sum(np.log(f)) (with c4 created before the loop). Note that Python do not have a JIT as opposed to Matlab so a direct translation is clearly not a good idea (like for any code translation from one language to another, including even natural languages). You should learn to use vectorization in Numpy (note that this is already important in Matlab for sake of performance). If c4 is a scalar, then use c4 = np.sum(np.log(f)) without loops. Commented Aug 16, 2022 at 14:55

2 Answers 2

1

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)))
Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.