Avoiding for loop with ismember
2 ビュー (過去 30 日間)
古いコメントを表示
Hi, suppose N is a scalar, and c is a numerical vector with unique elements that are a subset of 1:N, i.e. its size is smaller or equal to N. For example, N=4, and c=[1 2 4]'; Then, is there a more elegant way to achieve this?
cc = [];
for j = 1:N
if ismember(j,c)
cc = [cc; N*(j-1)+c];
end
end
Thanks!
2 件のコメント
採用された回答
Andrei Bobrov
2017 年 6 月 23 日
編集済み: Andrei Bobrov
2017 年 6 月 23 日
[Fixed]
N = 15;
c = randperm(N,4);
c1 = sort(c(:));
cc = reshape(bsxfun(@plus,N*(c1 - 1),c1')',[],1);
or
oc = ones(numel(c1),1);
cc = N*(kron(c1,oc) - 1) + kron(oc,c1);
or
c = c(:);
nn = numel(c);
cc = N*(repelem(c,nn) - 1) + repmat(c,nn,1);
6 件のコメント
Stephen23
2017 年 6 月 23 日
@Christian: With the data you have shown us cc will definitely be a matrix. If c is a column vector then you should specify this in your question.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!