If condition is met, find next instance of a certain value.

조회 수: 24 (최근 30일)
Sara LoTemplio
Sara LoTemplio 2021년 3월 13일
댓글: Walter Roberson 2021년 3월 13일
Hello- I have a vector of values. for example purposes, we can say it's this:
x = [1 223 224 225 226 2 222 223 224 225 226 3 223 224 225 226]
For values 1 and 2, I need to identify the next instance of the the number 226. As you can see, using (n+4) won't work because the number 226 is in a different position each time. Is there a function that allows you to find the next instance of 226 in the array?
For value 3, I need to find a different number- let's say 225. I know I can solve this with conditionals, but just including that as a limitation for certain solutions (ie. I can't just write a function that identifies all single digit integers).
  댓글 수: 1
Sergey Kasyanov
Sergey Kasyanov 2021년 3월 13일
Are you need to find relative position of the number (for example 226) for each element of array (for example 1)?

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

답변 (2개)

Sergey Kasyanov
Sergey Kasyanov 2021년 3월 13일
Hello,
If you have array with values that you need to find you can use that code:
values_to_find = [226 226 225 221 226 226 2 222 223 224 225 226 3 223 224 225 226];
x = [1 223 224 225 226 2 222 223 224 225 226 3 223 224 225 226] ;
relative_position_of_next_instance = zeros(1,length(x));
absolute_position_of_next_instance = zeros(1,length(x));
for i = 1:length(x)
f = find(x(i:end) == values_to_find(i), 1);
if ~isempty(f)
relative_position_of_next_instance(i) = f;
absolute_position_of_next_instance(i) = f + i - 1;
end
end

Walter Roberson
Walter Roberson 2021년 3월 13일
x = [1 223 224 225 226 2 222 223 224 225 226 3 223 2 224 225 226];
idx226 = find(x == 226).';
for_1 = idx226(1+sum(cumprod(find(x==1) > idx226)))
for_1 = 5
for_2 = idx226(1+sum(cumprod(find(x==2) > idx226)))
for_2 = 2×1
11 17
idx225 = find(x==225).';
for_3 = idx225(1+sum(cumprod(find(x==3) > idx225)))
for_3 = 16
Sooo....
Select = @(M,idx) M(idx);
x = [1 223 224 225 226 2 222 223 224 225 226 3 223 2 224 225 226];
basevals = [1 2 3];
targvals = [226 226 225];
outputs = arrayfun(@(b,t) Select(find(x==t), 1+sum(cumprod(find(x==b) > find(x==t).'))), basevals, targvals, 'uniform', 0)
outputs = 1×3 cell array
{[5]} {[11 17]} {[16]}
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 3월 13일
This code was designed for the possibility that there might be multiple copies of the value being looked for, and that in each case it is the next location of the target value that is to be returned. Thus in the above ssample x, there are two copies of 2, and the indices returned are those relevant to each of them separately.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by