Check if a value exists in a cell array starting from a value whose index is the desired value
조회 수: 6 (최근 30일)
이전 댓글 표시
Let's suppose:
A={5, 15, 0, [11, 7], 9, 0, [1, 20, 21], 18, [22,15], 0, 16, [13, 14], 17, 4, 6 };
a=6; b=1;
Now, I would like to know if I can get to b from a using the values as an index. In this case:
Value Index
6 -> 15
15 -> [2, 9]
for
2 -> Nan
9 -> 5
and
5 -> 1
Thanks
댓글 수: 0
채택된 답변
Dyuman Joshi
2023년 8월 14일
I have unsuppressed the output of variable temp to show the path that is followed (as you have demonstrated above) -
A={5, 15, 0, [11, 7], 9, 0, [1, 20, 21], 18, [22,15], 0, 16, [13, 14], 17, 4, 6 };
a=6; b=1;
B = [A{:}];
%maximum value present in A
m = max(B);
z1 = nested(A,6,1)
%Any value greater than the maximum value in the cell array will not be present
%So for any value of b, the output will be zero
z2 = nested(A,m+randi(100),randi(numel(A)))
z3 = nested(A,9,4)
%3rd value corresponds to zero, so the search is terminated for any value in A
z4 = nested(A,3,B(randi(numel(B))))
function z = nested(A,a,b);
%Returns 0 if not related, 1 if related
%Initialize z as 0
z=0;
nA=numel(A);
%Values corresponding to indices of elements in A
idx=1:numel(A);
%Check if b is present in a or not
if ismember(b,a)
z=1;
return;
%Return 1 if present, else continue checking
else
for k=1:numel(a)
%Check only if the values is within the range of number of elements of B
if a(k)>0 && a(k)<=nA
%Finding the index of the value
y=cellfun(@(x) ismember(a(k),x), A);
%Corresponding values
temp=idx(y)
z = nested(A,temp,b);
else
%If the value is not in the range, skip to the next iteration
continue;
end
end
end
end
댓글 수: 6
Dyuman Joshi
2023년 8월 14일
편집: Dyuman Joshi
2023년 8월 14일
I have edited it, this should work -
A = {1, 2};
a = 2;
b = 1;
z = nested(A,a,b)
function z = nested(A,a,b);
%Returns 0 if not related, 1 if related
%Initialize z as 0
z=0;
nA=numel(A);
%Values corresponding to indices of elements in A
idx=1:numel(A);
%Check if b is present in a or not
if ismember(b,a)
z=1;
return;
%Return 1 if present, else continue checking
else
for k=1:numel(a)
%Check only if the values is within the range of number of elements of B
if a(k)>0 && a(k)<=nA
%Finding the index of the value
y=cellfun(@(x) ismember(a(k),x), A);
%Corresponding values
temp=idx(y);
%If temp is equal to a, return 0, avoiding infinite recurison
if isequal(temp,a)
return;
end
z = nested(A,temp,b);
else
%If the value is not in the range, skip to the next iteration
continue;
end
end
end
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!