필터 지우기
필터 지우기

What is the best way to vectorize this matrix problem?

조회 수: 1 (최근 30일)
John Malik
John Malik 2017년 4월 27일
편집: Andrei Bobrov 2017년 4월 28일
I have a square matrix A which I would like to manipulate using a "map" matrix D. The result will be the matrix B. The entry B(i, j) will be a sum of a number of elements from A(:, j), as determined by D. In the following example, the matrix D tells me that A(1, 1) will be added with A(3, 1) to form B(1, 1), and so on. When the matrices are large, this process takes a long time. Is there a way to vectorize this computation?
A = magic(3); % initial matrix
D = [1, 2, 3; 2, 2, 3; 1, 3, 1]; % map matrix
B = zeros(3); % resultant matrix
for i = 1:3
for j = 1:3
B(D(i, j), j) = B(D(i, j), j) + A(i, j);
end
end

채택된 답변

John Malik
John Malik 2017년 4월 27일
This question has been answered here.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 4월 27일
편집: Andrei Bobrov 2017년 4월 28일
B = accumarray([D(:),repelem((1:size(D,2))',size(D,1))],A(:));

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by