필터 지우기
필터 지우기

Logical indexing and sums

조회 수: 1 (최근 30일)
Fabs
Fabs 2014년 5월 28일
댓글: Fabs 2014년 5월 28일
Hi,
first of: I know I can do what I want in a loop. However, I'm performing something similar to my problem thousands of times on much bigger matrices, so if there is a solution with logical indexing and without any loop, that would be preferred.
OK, let's assume I have a matrix
a=[23 45; 65 13];
and I want the values of a to written to new positions defined in
b=[2 4;1 2]; % matrix with new positions for values in a
Obviously b is referencing one position (2) twice and
c=nan(size(a));
c(b) = a % matrix with values from a at positions from b
results in
c = [65 13; NaN 45]; % location two is written twice and only the second value shows up
Is there a way to get matrix c to be
c = [65 36; NaN 45]; % location 2 is sum of 13+23
?
Thanks y'all, I appreciate your help, F

채택된 답변

Kelly Kearney
Kelly Kearney 2014년 5월 28일
Meet accumarray, my favorite powerful-and-useful-but-terribly-named function (and lately, seemingly the answer to every question I respond to):
c = reshape(accumarray(b(:), a(:), [numel(a) 1], @sum, NaN), size(a))
  댓글 수: 1
Fabs
Fabs 2014년 5월 28일
That's what I call a quick response! Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by