# Extract columns from matrix based on a vectors values

조회 수: 1(최근 30일)
Tom Hagéus 2020년 11월 6일
댓글: Jon 2020년 11월 6일
I want to extract the columns of a matrix A (mxn), based on a vector B's values into a new matrix C, meaning:
Which also should be dependent on B's dimensions (1xm):
For example:
A=[1,1,1,0;
2,1,0,1];
B=[3,4];
Then C should be:
C=[1,0;
0,1].
I want this to work for any dimensions of n and m.
I have tried:
C=A(:,B(1,1):1:B(1,size(B,2)))
but it doesn't work for B=[3,1] since it takes column by column.
Thanks!

댓글을 달려면 로그인하십시오.

### 채택된 답변

Jon 2020년 11월 6일
편집: Jon 2020년 11월 6일
I think this should do it for you:
C = A(:,B)
Jon 2020년 11월 6일

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

dpb 2020년 11월 6일
편집: dpb 2020년 11월 6일
>> A=[1,1,1,0;
2,1,0,1];
B=[3,4];
>> A(:,B)
ans =
1 0
0 1
>> B=[3,1];
>> A(:,B)
ans =
1 1
0 2
>>
meets the description of the vector B.
If you mean for B to be all columns from B(1):B(2) inclusive, then you have to be more explicit in how you write the expression:
>> A(:,B(1):sign(diff(B)):B(2))
ans =
1 1 1
0 1 2
>>
This will require that B always be a 2-vector and B(1)~=B(2).
##### 댓글 수: 1표시숨기기 없음
Tom Hagéus 2020년 11월 6일
Thanks, A(:,B) solved it!

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by