How to create a "scatter" matrix without using a for loop?
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ethan Chu
am 3 Jun. 2023
Beantwortet: Steven Lord
am 3 Jun. 2023
I am trying to create a matrix given size, x-coordinate, y-coordinate, and value. Ideally, I would like to avoid using a for loop as I usually work with large data sets.
For example, I have a 4x4 zero matrix.
M = zeros(4)
row = [1,2,3];
col = [2,4,4];
val = [123,321,456];
Is there a function or fast method turn this into:
M = [0 123 0 0;
0 0 0 321;
0 0 0 456;
0 0 0 0]
0 Kommentare
Akzeptierte Antwort
Cris LaPierre
am 3 Jun. 2023
M = zeros(4);
row = [1,2,3];
col = [2,4,4];
val = [123,321,456];
ind = sub2ind(size(M),row,col)
M(ind) = val
0 Kommentare
Weitere Antworten (1)
Steven Lord
am 3 Jun. 2023
row = [1,2,3];
col = [2,4,4];
val = [123,321,456];
M = accumarray([row.', col.'], val.', [4 4])
0 Kommentare
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!