Use vectors to index an 2D array
51 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
paganelle
am 16 Okt. 2020
Beantwortet: Star Strider
am 16 Okt. 2020
I have two 1D vectors with X and Y coordinates in 2D array and I want to assign (X,Y) cells some values:
X = [1 2 3 4];
Y = [4 3 2 1];
A(X,Y) = 1;
I.e. want to have only A(1,4), A(2,3), A(3,2) and A(4,1) equal to 1;
But if I run those 3 lines, I have an entire matrix A filled with ones. Of course I can do it in a loop, but I sure it should be the way to vectorize it.
0 Kommentare
Akzeptierte Antwort
Star Strider
am 16 Okt. 2020
X = [1 2 3 4];
Y = [4 3 2 1];
A = zeros(4);
Lidx = sub2ind(size(A), X, Y);
A(Lidx) = 1
producing:
A =
0 0 0 1
0 0 1 0
0 1 0 0
1 0 0 0
.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!