Thanh Ha
Thanh Ha

Reputation: 147

How to call index of vector in matrix in matlab?

I have: n-by-3 matrix A, and n-by-1 matrix B:

  A=[ x1 y1 z1           
      x2 y2 z2
      x3 y3 z3
      x4 y4 z4
      .......
      xn yn zn ]

B=[ 3           
    2
    7
    1
    ...
    n ]

B is index (labelling) matrix of A.

I wanna assign the vector A to vector B.

Ex:

(x1 y1 z1) assign to 1
(x3 y3 z3) assign to 3
......................

(xn yn zn) assign to n

Instead of working with matrix A, I can work with "labelling" matrix B. and then

from matrix A.

How to write a code to call matrix A from matrix B , and vice versa? (the numbers 3,2,7,1,....n: in matrix B are arbitrary numbers)

Detailed Example: I have: 6-by-3 matrix A

  A=[ 15 2 -1        ---> labelling "1"   
      51 6 -3        ---> labelling "2"
      89 9  1        ---> labelling "3"
      0  4  5        ---> labelling "4"
      0  0  9        ---> labelling "5"
      10 4 -5 ]      ---> labelling "6"

................................. ...I will do some algorithm....... ..................................

.................................. And, I get the "labelling matrix B" output result........

  B=[ 6           
      1 
      5 ]

I wanna to get back the value in matrix A from B-->

  C=[ 10 4 -5           
      15 2 -1
      0  0 9 ]

How to write a code to show the relationship between A, B,C ? (or how to call matrix C from A &B )

Upvotes: 0

Views: 171

Answers (2)

gnovice
gnovice

Reputation: 125854

Your indexing can be done simply with:

C = A(B, :);

In other words, B is just used as the row index into A to select the rows, and all the columns for those rows are selected with :.

Upvotes: 1

a = [1,2,3;
    4,5,6;
    7,8,9]
a(1,:)
a(2,:)
a(3,:)

a =

 1     2     3
 4     5     6
 7     8     9

ans =

 1     2     3

ans =

 4     5     6

ans =

 7     8     9

Upvotes: 1

Related Questions