Check if a value exists in a cell array starting from a value whose index is the desired value
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sergio Rojas Blanco
am 14 Aug. 2023
Kommentiert: Sergio Rojas Blanco
am 14 Aug. 2023
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 Kommentare
Akzeptierte Antwort
Dyuman Joshi
am 14 Aug. 2023
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 Kommentare
Dyuman Joshi
am 14 Aug. 2023
Bearbeitet: Dyuman Joshi
am 14 Aug. 2023
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!