フィルターのクリア

Simple but elusive array question

1 回表示 (過去 30 日間)
Will
Will 2012 年 4 月 17 日
Hi,
I have what must be quite a straightforward question, but I can't find a good solution.
I have a large number of arrays, of dimension 500x40. Each column of the arrays consists of a number of (non-repeating) integers between 1 and 40, with the remaining elements being zeros. An example of this on a smaller array would look like this:
1 1 3
2 0 4
3 0 0
0 0 0
What I want to do, is use this to create an array of the same dimensions, which consists of zeros and ones, such that for each column, the entries in that column are the indices of the "ones", and the remaining elements are zero. So, for the example above, I would get:
1 1 0
1 0 0
1 0 1
0 0 1
The catch is, I was trying to think of a nice way of doing it without using for loops, because I have a large number of arrays and want things to run quickly.
I'm sure there must be a very simple solution to this, but I can't think of it!
Any thoughts? Thanks, Will

採用された回答

Oleg Komarov
Oleg Komarov 2012 年 4 月 17 日
[r,c,v] = find(a);
out = accumarray([v,c],1,size(a));
  3 件のコメント
Will
Will 2012 年 4 月 17 日
Thank you, that is a very nice solution!
Sean de Wolski
Sean de Wolski 2012 年 4 月 17 日
+1, anything with accumarray or bsxfun gets a vote!

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2012 年 4 月 17 日
A = [1 1 3
2 0 4
3 0 0
0 0 0]
s1 = size(A);
out = zeros(size(A));
t = A~=0;
A1 = bsxfun(@times,t,1:s1(2));
out(sub2ind(s1,A(t),A1(t))) = 1
  1 件のコメント
Will
Will 2012 年 4 月 17 日
Thanks!

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


Richard
Richard 2012 年 4 月 17 日
should your question be like 'a' below?
clear all
a = [1,1,3;2,0,4;3,0,0;0,0,0];
b = arrayfun(@find,a,'un',0);
If so, use find and then just replace the empty cells with zeros.
  1 件のコメント
Will
Will 2012 年 4 月 17 日
No, the ones should correspond to the indices of the values. Oleg has posted a very nice answer which does this. Thanks for your help though!

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

カテゴリ

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