2
$\begingroup$

This may be a simple question, but how can I find a column vector in a matrix? As an example, A = {{1, 2}, {0, 1}} b = {1, 0}; $$\\ A=\biggl( \begin{matrix} 1 & 2 \\ 0 & 1 \end{matrix} \biggr)$$ $$\\ b=\biggl( \begin{matrix} 1 \\ 0 \end{matrix} \biggr)$$

$\endgroup$
5
  • 1
    $\begingroup$ A[[All,1]] gives the first column of the matrix A. Look at ‘Part’ for other ways to index into lists and matrices $\endgroup$
    – bill s
    Commented Sep 30, 2017 at 3:20
  • 2
    $\begingroup$ Why not transpose the matrix and find a row instead? $\endgroup$ Commented Sep 30, 2017 at 3:52
  • $\begingroup$ Thank you both. Unfortunately, I can't figure out how to use Part to actually find the index of the pertinent column instead of checking each column against b. I will try transposing the matrix though, thanks. $\endgroup$
    – BJParks
    Commented Sep 30, 2017 at 18:11
  • $\begingroup$ why is every one making this simple operation so complicated? :) Bill comment above is all what is needed. A[[ All , columnNumber ]] This maps 1:1 to Matlab A(:,ColumnNumber) Except Mathematica uses [[ for Matlabs ( and All for Matlab : $\endgroup$
    – Nasser
    Commented Sep 30, 2017 at 20:34
  • $\begingroup$ @Nasser, I was assuming this was a toy example, and OP does need to find out which column of a given matrix is identical to a given list, in which case transposition is a useful first step. $\endgroup$ Commented Sep 30, 2017 at 22:05

2 Answers 2

2
$\begingroup$
A = {{1, 2, 1}, {0, 1, 0}};
b = {1, 0};
Pick[Range[Length[First[A]]], Transpose[A], b]

{1, 3}

$\endgroup$
2
  • $\begingroup$ Thank you! This does exactly what I need. $\endgroup$
    – BJParks
    Commented Sep 30, 2017 at 19:34
  • $\begingroup$ I personally would've used Last[Dimensions[A]] instead of Length[First[A]]. $\endgroup$ Commented Oct 1, 2017 at 7:07
1
$\begingroup$

One method as suggested by J.M. (written two equivalent ways):

hk = Partition[A // Transpose, Length[A[[All, 1]]]] // Transpose;
{{c, d}} = Position[hk, b];
A[[All,c]]


{{c, d}} =  Position[Transpose[Partition[Transpose[A], Length[A[[All, 1]]]]], b]
A[[All,c]]
$\endgroup$
2
  • 4
    $\begingroup$ Why are you using Partition? Couldn't you simply Position[A\[Transpose], b]? $\endgroup$
    – Szabolcs
    Commented Sep 30, 2017 at 19:07
  • $\begingroup$ Thank you, this works very well also; I didn't realize that Position could be used like that. $\endgroup$
    – BJParks
    Commented Sep 30, 2017 at 19:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.