简体   繁体   中英

With a python matrix M (using numpy), how can I compare each column of that matrix with all other columns?

I want to see whether there is a way to compare a column of a matrix with all other columns of the same matrix, without using loops. Obviously the result can be extremely large and for a [mxn] matrix will grow in size with n**2. But with reasonable values n it is hopefully possible.

Concretely I have a matrix like:

|  1  -1  1  1  -1 |
| -1  -1  1  1   1 |
| -1   1 -1 -1   1 |
|  1  -1  1 -1   1 |

And need to get AND and XOR values (or other logical comparisons) for all combinations of columns. Is this possible without loops? I am relatively new to Python, R and Octave, but have encountered similar problems already several times. So a solution in Python or other languages would be most welcome!

Example:

| 1 -1  1 |     | 2 0 2 0 -2 0 2 0  1 | 
| 1  1 -1 |  => | 2 2 0 2  2 0 0 0 -2 |
|-1  1  1 |     |-2 0 0 0  2 2 0 2  2 |

[ column 1 + matrix , column 2 + matrix , column 3 + matrix ]

It's getting big very fast. There is a lot of duplication, for example I do not need to have a column added to itself, and I do not really need to compare each column with all other columns, but better with all the columns with higher column number (on the right side). Perhaps it is easier to implement it like example above. And maybe it is just not possible! I can imagine this is the kind of function that quickly absorbs all available memory!

I don't know whether there is some inbuilt mechanism for your problem solution or not. But I have something which may helpful to you.

import numpy as np
a = np.random.random_integers(0,6,(300,300))
b = np.random.random_integers(0,6,(300,300))

for i in xrange(300):
    a = np.roll(a, 1, axis=a)
    ###Do whatever you want to do with a and b

here all combination of matrix a will be generated so you can use it as per your use.

And you don't want to use loops may be because of time efficiency. but this will work faster because of numpy improved library

I'm writing the answer on StackOverflow for the first time. So, if you find it's wrong then sorry!

refrance: http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM