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]
댓글 수: 0
채택된 답변
Cris LaPierre
2023년 6월 3일
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
추가 답변 (1개)
Steven Lord
2023년 6월 3일
row = [1,2,3];
col = [2,4,4];
val = [123,321,456];
M = accumarray([row.', col.'], val.', [4 4])
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!