0

I have this line in some matlab script that Im trying to convert to python. So, m=20, and n=20. The dimensions of I_true equals [400,1].

I want to convert following Matlab code:

A=zeros((2*m*n),(2*m*n)+2);
A(1:m*n,(2*m*n)+1)=-I_true(:);

Am I converting it right?

Converted code in Python:

for i in range(0,m*n):
    for j in range((2*m*n)+1):
        A[i][j] = I_true[i]
2
  • Your purpose is not clear enough. do you want to create a matrix? Commented May 21, 2016 at 11:02
  • Im trying to understand this operation in matlab, btw A is initialised as A=zeros((2*mn),(2*mn)+2); let me add it in the edit Commented May 21, 2016 at 12:08

2 Answers 2

1

Let's look at a small example, with n = 2, m = 2: In Octave (and presumably Matlab):

octave:50> m = 2; n = 2;
octave:51> I_true = [1;2;3;4];
octave:52> A = zeros((2*m*n),(2*m*n)+2);
octave:53> A(1:m*n,(2*m*n)+1)=-I_true(:)
A =

   0   0   0   0   0   0   0   0  -1   0
   0   0   0   0   0   0   0   0  -2   0
   0   0   0   0   0   0   0   0  -3   0
   0   0   0   0   0   0   0   0  -4   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0

The equivalent in Python (with n = 20, m = 20) would be

import numpy as np
n, m = 20, 20
I_true = np.arange(1, n*m+1)  # just as an example
A = np.zeros((2*m*n, 2*(n*m+1)), dtype=I.dtype)
A[:m*n, 2*m*n] = -I_true

The reason why the last line uses A[:m*n, 2*m*n] and not A[1:m*n, (2*m*n)+1] is because Python uses 0-based indexing whereas Matlab uses 1-based indexing.

Sign up to request clarification or add additional context in comments.

Comments

0

Check this so question as well.

You can define a matrix with 2*m*n rows and 2*m*n+2 columns in python like this:

m = 20
n = 20
a = [[0 for i in range(2*m*n)] for j in range((2*m*n)+2)]

Now you have your matrix you can assign values to its elements using different ways. One example would be using for loops to assign values from another matrix with same size:

for i in range(2*m*n):
    for j in range((2*m*n)+2):
        a[i][j] = I_true[i][j]

I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.