adding to a matrix with

1 回表示 (過去 30 日間)
ily
ily 2011 年 8 月 26 日
I want to add one to the matrix A for each time the respective linear index appears in the vector Ex. lin_ind =
1 1 3 5 5 7 9 9 11 13 13
A = zeros(8, 8)
I want A(1) = 2 because 1 appears twice. A(2) = 0. A(3) = 1.
  2 件のコメント
Chaowei Chen
Chaowei Chen 2011 年 8 月 27 日
just comment on "I want A(1) = 2 because 1 appears twice. A(2) = 0. A(3) = 1. "
This is histogram. A=hist(lin_ind,1:64);A=reshape(A,[8 8]);
Walter Roberson
Walter Roberson 2011 年 8 月 27 日
Good point about it being a histogram.
I did some timing, and on my system,
A=reshape(accumarray(lin_ind(:),1,[64 1]),[8,8]);
is about twice as fast as
A=reshape(hist(lin_ind,1:64),[8,8]);
when tried with the lin_ind given above. I did not try with a larger lin_ind

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2011 年 8 月 27 日
You create an 8 x 8 array, and then you specify the additions in terms of 1-dimension indices, and from your question you clearly want gaps of 0 where there is no linear index with the corresponding value. The maximum value of your example lin_id is 13: does that mean you would want A(13) = 2 ? If so, then should that A(13) correspond to A(2,5), the 13th element of your 8 x 8 array? If so, then:
A = zeros(8,8);
t = accumarray(lin_ind(:),1);
A(1:length(t)) = A(1:length(t)) + t;
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2011 年 8 月 27 日
Hi Walter!
variant
[I,J] = ind2sub([8 8],lin_ind)
A = accumarray([I',J'] ,1,[8 8])
ily
ily 2011 年 8 月 28 日
Thanks, both are great solutions. I actually have the positions specified in row and column subscripts and I converted it to linear indices, so andrei's solution allows me to skip that step. I didn't know of the accumarray function before.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by