Elementwise indexing of a vector by a multidimentional array

2 vues (au cours des 30 derniers jours)
Louis Exley
Louis Exley le 18 Jan 2022
Réponse apportée : DGM le 18 Jan 2022
I have:
  • A, an n-dimentional array of integers, whose values are in the range 1-100,
  • and T, a 1-dimentional, length 100 array of values.
I want a new n-dimentional array B which, for each corresponding (same position) integer c of A, has the value T(c).
What is the proper way to do this without a for loop, preferrably that works on a gpuArray?

Réponses (2)

KSSV
KSSV le 18 Jan 2022
n = 10 ;
A = randi(n,2,2,10) ;
B = rand(1,n) ;
iwant = B(A)
iwant =
iwant(:,:,1) = 0.6011 0.4264 0.6566 0.7867 iwant(:,:,2) = 0.0678 0.6011 0.2322 0.6011 iwant(:,:,3) = 0.0678 0.4264 0.2878 0.2322 iwant(:,:,4) = 0.9453 0.2322 0.6598 0.0678 iwant(:,:,5) = 0.7867 0.6598 0.9453 0.7867 iwant(:,:,6) = 0.4264 0.0678 0.5672 0.2322 iwant(:,:,7) = 0.2878 0.9453 0.0678 0.9453 iwant(:,:,8) = 0.9453 0.9453 0.6566 0.6566 iwant(:,:,9) = 0.6598 0.4264 0.6566 0.6566 iwant(:,:,10) = 0.6566 0.5672 0.5672 0.2878

DGM
DGM le 18 Jan 2022
I have no idea what's ideal for gpuArray, but this is how it would be done with linear indexing.
T = 11:20; % a vector
A = randi([1 10],2,2,2) % a 3D array
A =
A(:,:,1) = 3 8 5 2 A(:,:,2) = 10 3 6 9
B = T(A) % linear indexing
B =
B(:,:,1) = 13 18 15 12 B(:,:,2) = 20 13 16 19

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by