how to do something like A(:,B(:)) ?

조회 수: 8 (최근 30일)
SebLambert
SebLambert 2013년 9월 25일
Hello everybody,
I have a matrix A of size n x p, e.g. 10*4
A =
0.2760 0.7513 0.8407 0.3517
0.6797 0.2551 0.2543 0.8308
0.6551 0.5060 0.8143 0.5853
0.1626 0.6991 0.2435 0.5497
0.1190 0.8909 0.9293 0.9172
0.4984 0.9593 0.3500 0.2858
0.9597 0.5472 0.1966 0.7572
0.3404 0.1386 0.2511 0.7537
0.5853 0.1493 0.6160 0.3804
0.2238 0.2575 0.4733 0.5678
and a vector B (1 x n), e.g.
B =
2 2 4 4 1 2 2 3 3 4
and I would like to build a vector C (1 x n) where C(k) = A(k,B(k)) (in my example I would like to get C = [0.7513 0.2551 0.5853 .......] I thought I was pretty comfortable with matlab syntax but I'm lost there ! :) if anyone has any idea ...

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 25일
nm=size(A)
C=A(sub2ind(nm,1:nm(1),B))
  댓글 수: 2
SebLambert
SebLambert 2013년 9월 25일
ok thank you very much ! that is where I was arriving myself :) but then if A is n x p x q and B is n x p, I have to do something like :
[X,Y] = ndgrid(1:size(A,1),1:size(A,2));
A(sub2ind(size(A),X,Y,B))
Am I right ?
Azzi Abdelmalek
Azzi Abdelmalek 2013년 9월 25일
It's true

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

추가 답변 (1개)

Youssef  Khmou
Youssef Khmou 2013년 9월 25일
you can create your vectors as the following :
C1=A(:,B(1));
C2=A(:,B(2));
C4=A(:,B(4));
  댓글 수: 1
SebLambert
SebLambert 2013년 9월 25일
thanks for your answer but I guess that is not what I want to do :) I want to have only one vector where the kth element is A(k,B(k))

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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by