Bed of Nails from vectors - inverse of find()?

1 回表示 (過去 30 日間)
Douglas Anderson
Douglas Anderson 2018 年 2 月 27 日
コメント済み: Jos (10584) 2018 年 2 月 28 日
Hello,
I would like to do the following:
X = zeros(N,M); % Say N = 50, M = 100
Then have N sets of indices, one for each row of X:
a(1,:) = [ 1 5 10 12 19 32 56 ...]; % These may vary substantially
a(2,:) = [ 1 7 14 19 29 45 76 ...];
...
These are then indices that will indicate where there should be a "1" in each row of X.
Is there a function that will take the indices and then put a "1" in an array? This is kind of like the inverse of find().
Thanks!
Doug Anderson
  2 件のコメント
Jos (10584)
Jos (10584) 2018 年 2 月 27 日
As your variable a is a N-by-K matrix, this assumes that all rows of X will hold K ones. Is that so?
Douglas Anderson
Douglas Anderson 2018 年 2 月 27 日
Yes, that is true.

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

採用された回答

Jos (10584)
Jos (10584) 2018 年 2 月 27 日
% input
N = 5 ; M = 4 ;
a = [1 3 ; 2 4 ; 1 4 ; 1 2 ; 3 4]
% engine in one line
XX = full(sparse(repmat(1:N, size(a,2), 1)', a, 1,N,M))
  2 件のコメント
Douglas Anderson
Douglas Anderson 2018 年 2 月 27 日
Thanks to everyone. Of course, this is only the deepest level of a bunch of calculations to determine the "a" values, so this one-line engine is nice.
Can you tell me why this works? :) Thank you!
Jos (10584)
Jos (10584) 2018 年 2 月 28 日
This might not be the most efficient way though.
See the documentation of sparse for more details.

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

その他の回答 (2 件)

Sean de Wolski
Sean de Wolski 2018 年 2 月 27 日
for ii = 1:size(x, 1)
x(ii, a(ii,:)) = 1;
end

Jos (10584)
Jos (10584) 2018 年 2 月 27 日
N = 5 ; M = 4 ;
a = [1 3 ; 2 4 ; 1 4 ; 1 2 ; 3 4]
X = zeros(N,M)
X(sub2ind([N M], repmat(1:N, size(a,2), 1)', a)) = 1

カテゴリ

Help Center および File ExchangeSimulink についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by