1

I have a matrix

1   2   3
4   5   6
7   8   9

I want to combine the first element with the other element of the same matrix and create new matrix.

x and y is ndarray I want to do this code in python

for i=0 to 3 do
    for j=0 to 3 do
      if  x[0][0]<x[i][j] then 
            t[i][j]=1
      else
           t[i][j]=0

In python:

x=np.array([[1,2,3], [4,5,6], [7,8,9]])
y=[]
for i in range(0, 3):
    for j in range(0, 3):
        if x[0][0]< x[i][j]:
            y.append(1)
        else:
            y.append(0)

out put:

>>> t
[0, 1, 1, 1, 1, 1, 1, 1, 1]

Is this statement correct ?

1
  • 1
    this is a very confusing question .... Commented Jul 31, 2013 at 23:37

2 Answers 2

3

First, when I run your code exactly as stated, I get this value for y, not the value you pasted:

[0, 1, 1, 1, 1, 1, 1, 1, 1]

I suspect what you're trying to do is not actually what you have written here, but assuming it is, here's a much easier way to achieve the same result:

>>> np.where(x > x[0,0], 1, 0).flatten()
array([0, 1, 1, 1, 1, 1, 1, 1, 1])
Sign up to request clarification or add additional context in comments.

1 Comment

what? didn't you just provide your own answer?
0

I think you want something like

x=np.array([[1,2,3], [4,5,6], [7,8,9]])
output = []
for i in range(0, 3):
    y=[]
    for j in range(0, 3):
        if x[0][0]< x[i][j]:
            y.append(1)
        else:
            y.append(0)
     output.append(y)
print output

but its kind of hard to tell from your question

but a better solution would be

map(lambda tmp:map(int,tmp),(x+x[0,0])[0,0] < x)

or even better use jterraces solution with numpy

3 Comments

but if I want to combine the element x[1][1] this gives >>> output [[0, 1, 1], [1, 1, 1], [1, 1, 1], [0, 0, 0], [0, 0, 1], [1, 1, 1]], normally it gives me a matrix of 3 lines and 3 columns.>>> output [[0, 1, 1], [1, 1, 1], [1, 1, 1]],
I dont understand what you mean by "combine the element x[1][1]"
it means:x[1][1]=5 combine with all x[i][j] (2,3,4,5,6,7,8,9), if 5<2 then y[0][1]=1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.