find value every time counter increase by 2.

조회 수: 2 (최근 30일)
A-Rod
A-Rod 2024년 3월 8일
댓글: Voss 2024년 3월 11일
hello community kindly let me ask your support:
I have 2 vectors:
a = [0 0 0 0 1 1 2 2 3 3 3 3 4]'; %Counter
b = [0 1 2 3 4 5 6 7 8 9 10 11 12]'; %value to be found
c = [0 0 0 0 0 1 1 0 0 0 0 0 1]'; %flag when condition is met
what I'm trying to do is to get a value from b every time a increases its value by 2 and when c = 1
for j=1:length(time)
if a(j) == a(j) ++2 && c == 1
d(j,1) = b(j);
end
I'm trying to get something like:
d = [ 0 0 0 0 0 0 6 0 0 0 0 12]
can not find the solution......
any advice will be highly appreciated.
  댓글 수: 2
John D'Errico
John D'Errico 2024년 3월 8일
Your example does not match what you asked.
a = [0 0 0 0 1 1 2 2 3 3 3 3 4]
a NEVER increases its value by 2 from the previous element in that vector.
Are you asking to find when a has increased by 2 from the previous case you found? So there the 6th element is 2 greater than 0, the start of the vector. But what are you asking?
A-Rod
A-Rod 2024년 3월 8일
Thank you John to take time to look at my question.
I didn't meant to say previous element in that vector a.
I meant to say everytime counter a increases its value by two from the start of the vector which is 0
when a = 2 and then a = 4 and so on.....

댓글을 달려면 로그인하십시오.

채택된 답변

Voss
Voss 2024년 3월 8일
a = [0 0 0 0 1 1 2 2 3 3 3 3 4]'; %Counter
b = [0 1 2 3 4 5 6 7 8 9 10 11 12]'; %value to be found
c = [0 0 0 0 0 1 1 0 0 0 0 0 1]'; %flag when condition is met
Indices of a that are 0,2,4,6,8,... more than the first element of a, and where c is not zero:
idx = mod(a-a(1),2) == 0 & c;
Or indices of a that are 0,2,4,6,8,... more than the first element of a, and where c is not zero, and it's the first time hitting that value in a (assuming a never decreases from one element to the next):
idx = mod(a-a(1),2) == 0 & c & [false; diff(a) > 0];
idx is the same in both cases, for the example posted.
Construct d:
d = zeros(size(b));
d(idx) = b(idx);
disp(d)
0 0 0 0 0 0 6 0 0 0 0 0 12
Another example; this time the choice of method makes a difference because c(8) is 1, so you have two consecutive 2's in a, with c being 1 at both locations (Do you want to have both in d or just the first one?):
a = [0 0 0 0 1 1 2 2 3 3 3 3 4]'; %Counter
b = [0 1 2 3 4 5 6 7 8 9 10 11 12]'; %value to be found
c = [0 0 0 0 0 1 1 1 0 0 0 0 1]'; %flag when condition is met
idx1 = mod(a-a(1),2) == 0 & c;
d1 = zeros(size(b));
d1(idx1) = b(idx1);
disp(d1)
0 0 0 0 0 0 6 7 0 0 0 0 12
idx2 = mod(a-a(1),2) == 0 & c & [false; diff(a) > 0];
d2 = zeros(size(b));
d2(idx2) = b(idx2);
disp(d2)
0 0 0 0 0 0 6 0 0 0 0 0 12
  댓글 수: 2
A-Rod
A-Rod 2024년 3월 11일
It works, thanks a lot for sharing it
Voss
Voss 2024년 3월 11일
You're welcome!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by