How to create a "scatter" matrix without using a for loop?

12 次查看(过去 30 天)
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]

采纳的回答

Cris LaPierre
Cris LaPierre 2023-6-3
i think sub2ind will do the trick.
M = zeros(4);
row = [1,2,3];
col = [2,4,4];
val = [123,321,456];
ind = sub2ind(size(M),row,col)
ind = 1×3
5 14 15
M(ind) = val
M = 4×4
0 123 0 0 0 0 0 321 0 0 0 456 0 0 0 0

更多回答(1 个)

Steven Lord
Steven Lord 2023-6-3
row = [1,2,3];
col = [2,4,4];
val = [123,321,456];
M = accumarray([row.', col.'], val.', [4 4])
M = 4×4
0 123 0 0 0 0 0 321 0 0 0 456 0 0 0 0

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by