find value every time counter increase by 2.
1 view (last 30 days)
Show older comments
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 Comments
John D'Errico
on 8 Mar 2024
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?
Accepted Answer
Voss
on 8 Mar 2024
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)
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)
idx2 = mod(a-a(1),2) == 0 & c & [false; diff(a) > 0];
d2 = zeros(size(b));
d2(idx2) = b(idx2);
disp(d2)
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!