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
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))';
채택된 답변
추가 답변 (2개)
Andrei Bobrov
2013년 10월 21일
R = cumsum(~K).*~K;
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
2013년 10월 21일
Walter Roberson
2013년 10월 21일
n = nnz(K);
R = zeros(size(K,1),1);
R( K ~= 0 ) = 1:n;
카테고리
도움말 센터 및 File Exchange에서 Simulink에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!