Select values of a matrix given a matrix of indices?

Hi, suppose we have a matrix
A=rand(10,10);
Now I have two matrices:
x=[2,3;5,7]; y=[4,6;1,2];
Now I want to create a new matrix
B
where
B(1,1)=A(2,4); B(1,2)=A(3,4);
B(2,1)=A(5,1); B(2,2)=A(7,2);
is there any fast way to do this?

 Risposta accettata

"is there any fast way to do this?"
Use SUB2IND:
A = rand(10,10)
A = 10×10
0.5450 0.4398 0.6459 0.0467 0.0277 0.6175 0.5870 0.0939 0.0574 0.3836 0.0221 0.8333 0.1351 0.9740 0.2953 0.3260 0.2291 0.8171 0.1627 0.5144 0.2870 0.6653 0.1350 0.4574 0.9536 0.2163 0.3253 0.8696 0.7515 0.1564 0.2181 0.7151 0.9130 0.3128 0.5931 0.8399 0.4864 0.9117 0.2175 0.0121 0.2511 0.4902 0.4122 0.5957 0.4164 0.4223 0.1483 0.1979 0.5693 0.3208 0.4414 0.4948 0.7042 0.5923 0.9989 0.6687 0.5911 0.0469 0.9779 0.6344 0.3875 0.1796 0.7852 0.9598 0.3292 0.1749 0.0369 0.5410 0.0619 0.3418 0.1312 0.7621 0.0942 0.8692 0.7387 0.6949 0.4989 0.6069 0.6606 0.0878 0.7811 0.2260 0.5669 0.3541 0.4226 0.1288 0.5321 0.9633 0.0195 0.2571 0.0892 0.5916 0.4890 0.9875 0.5667 0.2207 0.7688 0.8158 0.5442 0.9627
x = [2,3;5,7];
y = [4,6;1,2];
idx = sub2ind(size(A),x,y);
B = A(idx)
B = 2×2
0.9740 0.2163 0.2511 0.1796

Più risposte (0)

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by