1
$\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$
  • 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 Sep 30 '17 at 3:20
  • 2
    $\begingroup$ Why not transpose the matrix and find a row instead? $\endgroup$ – J. M. will be back soon Sep 30 '17 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 Sep 30 '17 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 Sep 30 '17 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$ – J. M. will be back soon Sep 30 '17 at 22:05
2
$\begingroup$
A = {{1, 2, 1}, {0, 1, 0}};
b = {1, 0};
Pick[Range[Length[First[A]]], Transpose[A], b]

{1, 3}

$\endgroup$
  • $\begingroup$ Thank you! This does exactly what I need. $\endgroup$ – BJParks Sep 30 '17 at 19:34
  • $\begingroup$ I personally would've used Last[Dimensions[A]] instead of Length[First[A]]. $\endgroup$ – J. M. will be back soon Oct 1 '17 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$
  • 3
    $\begingroup$ Why are you using Partition? Couldn't you simply Position[A\[Transpose], b]? $\endgroup$ – Szabolcs Sep 30 '17 at 19:07
  • $\begingroup$ Thank you, this works very well also; I didn't realize that Position could be used like that. $\endgroup$ – BJParks Sep 30 '17 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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