how to create a vector of consecutive numbers that skip over certain elements

I have a vector K whose elements are either 1 or 0 and whose length may change depending on other inputs. I want code that will create a vector R with equal number of elements as K that equals consecutive numbers (1, 2, 3...) except where K=1. Where K=1 I want R to equal 0.
For instance
K might be:
K=[0; 0; 1; 0; 0; 1; 1; 0; 0; 1]
then I would like syntax that creates R as:
R=[1; 2; 0; 3; 4; 0; 0; 5; 6; 0]
Thanks for the help

1 件のコメント

Meshooo
Meshooo 2013 年 10 月 21 日
You can do like that
K = [0; 0; 1; 0; 0; 1; 1; 0; 0; 1];
M = ~K;
L = (1:length(K))')
R = (immultiply(L, M))';

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

 採用された回答

Jos (10584)
Jos (10584) 2013 年 10 月 21 日
Another approach:
K=[0; 0; 1; 0; 0; 1; 1; 0; 0; 1]
R = cumsum(K==0)
R(K==1) = 0

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2013 年 10 月 21 日
編集済み: Walter Roberson 2013 年 10 月 21 日
R = (1:length(K)).';
R(K==1) = 0;
Or
R = (1:length(K)).' .* (1-K);

2 件のコメント

Jacob
Jacob 2013 年 10 月 21 日
Thanks. I think this is close, but not exactly what I asked for. Both code snippets you posted would give me the following:
K=[0; 0; 1; 0; 0; 1; 1; 0; 0; 1]
then I would like syntax that creates R as:
R=[1; 2; 0; 4; 5; 0; 0; 8; 9; 0]
What I want is something that will recreate this:
K=[0; 0; 1; 0; 0; 1; 1; 0; 0; 1]
then I would like syntax that creates R as:
R=[1; 2; 0; 3; 4; 0; 0; 5; 6; 0]
So, the consecutive numbering "skips" over the zeros.
n = nnz(K);
R = zeros(size(K,1),1);
R( K ~= 0 ) = 1:n;

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

カテゴリ

ヘルプ センター および File ExchangeSimulink についてさらに検索

製品

タグ

質問済み:

2013 年 10 月 21 日

回答済み:

2013 年 10 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by