Counting how many steps a value stays within a certain percentage in an array
1 view (last 30 days)
Show older comments
I have an example array
[100 99 103 98 87 88 94 100]
I want to go through the array once for each value. I want to calculate how many steps I take from each value and stay within 10% of that value. For example, with the first value (100) I want to count how many steps I can take before the values stop being within 10% in either direction (in this case, how many steps fall between 90-110). Once a value is more than 10%, I want it to stop and move to the next number, regardless of whether the array returns to be within 10% later in the array or not.
The output I'm looking for is an array of identical length o the first array, with a corresponding value in the output for each input value.
I have tried tinkering with cumsum and feel this is how I'd get it done, but I'm getting no luck. Any help would be gratefully appreciated
0 Comments
Answers (1)
Andrei Bobrov
on 11 Mar 2014
Edited: Andrei Bobrov
on 11 Mar 2014
A = [100 99 103 98 87 88 94 100]
x = abs(bsxfun(@rdivide,bsxfun(@minus,A,A'),A)) <= .1;
y = cumsum([true(1,numel(A));diff(z)] == 1).*x;
z = bsxfun(@eq,y,diag(y)')
out = sum(z)
OR
A = A(:);
n = numel(A);
z = zeros(n);
for jj = 1:n
x = abs((A - A(jj))/A(jj) ) <= .1;
y = bwlabel(x);
% or without image toolbox -> y = cumsum([true;diff(x) == 1]).*x
z(:,jj) = y == y(jj);
end
out = sum(z);
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!