0

I have been trying for a couple of days to implement a simple program from a Matlab code to Python. I am using numpy but if there is a better way I am open to it.

This is my Matlab code:

x=[1,1,1,9];
A=zeros(length(x),length(x));
for i=length(x):-1:1
    for j=length(x):-1:i
        if i==length(x)
            A(i,j)=x(i);
        else
            if j>i
                A(i,j)=A(i+1,j)+(j-i);
            elseif j==i
                A(i,j)=x(i)+min(A(j+1,j+1:end));
            end
        end
    end
end
y=min(A(1,:));

It creates this matrix:

 12    12    13    15
 0    11    11    12
 0     0    10    10
 0     0     0     9

and the final result is 12 (the minimum from the first row). This is what I have done in Python so far:

import numpy as np

items = np.array([1,1,1,9])
sizeLimit = len(items)
P = np.zeros((len(items),len(items)))

for i in range(0, sizeLimit):
  for j in range(i, sizeLimit):
    if i == sizeLimit-1:
        P[i,j] = items[i]
    else:
        if j > i:
            P[i,j] = P[i+1,j] + [j-i]
        elif j == i:
            P[i,j] = items[i] + P[0, 0:].min()
print P

It seems it gets stuck somewhere and does not iterate.

I would be grateful to any help.

1
  • 1
    Is hard to understand your code. Can you explain what is this intended to do? I mean, what pattern you want to get in the matrix? Commented Nov 24, 2013 at 22:17

1 Answer 1

1

I've managed to replicate your Matlab result with:

import numpy as np

items = np.array([1,1,1,9])
sizeLimit = len(items)
P = np.zeros((len(items),len(items)))

for i in range(sizeLimit-1, -1, -1):
  for j in range(sizeLimit-1, i-1, -1):
    if i == sizeLimit-1:
        P[i,j] = items[i]
    else:
        if j > i:
            P[i,j] = P[i+1,j] + [j-i]
        elif j == i:
            P[i,j] = items[i] + P[j+1, (j+1):].min()

Giving me

>>> print P
[[ 12.  12.  13.  15.]
 [  0.  11.  11.  12.]
 [  0.   0.  10.  10.]
 [  0.   0.   0.   9.]]

The key point is to translate things like:

octave:1> 4:-1:1
ans =

   4   3   2   1

into

>>> sizeLimit = 4
>>> range(sizeLimit-1, -1, -1)
[3, 2, 1, 0]

In your original Python code things are reversed. range also excludes the end-point, unlike the Matlab function. You also need to be careful to account for the fact that unlike Matlab, Python has 0-based indexing.

2
  • 1
    Thank you so much. It's working perfectly. I was aware of 0-based indexing and tried many combinations last two days but couldn't make it work. I knew I was close :). Thanks again. Commented Nov 24, 2013 at 22:59
  • No problem. Have been through the same kinds of issues in the past many times. Commented Nov 24, 2013 at 23:06

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.