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

21 次查看(过去 30 天)
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 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by