% Function Name: deepestCell % Inputs (1): - (cell) A 1-dimensional cell array c
ID: 3537721 • Letter: #
Question
% Function Name: deepestCell
% Inputs (1): - (cell) A 1-dimensional cell array containing any number of
% nested cells
% Outputs (2): - (double) The index at which the most nested cell is found
% - (double) The "depth" of the most nested cell
%
% Function Description:
% Write a function called "deepestCell" that takes in a cell array of
% nested cells and determines the index at which the most nested cell is
% located and how deep that nested cell is. The "depth" is defined as how
% many nested cells the data are contained in, and does *NOT* include the
% enclosing cell array. If there are two deepest cells, then the function
% should return the lowest index. For further description of cell
% "depth", please see below:
%
% Given the cell array:
% exampleCA = {{'Drive safely!'}, {{{{[false false false]}}}}, {{8}}}
%
% - The depth of the cell in the first position of exampleCA is 1,
% because there is 1 nested cell inside of the cell array.
% - The depth of the cell in the second position of exampleCA is 4,
% because there are 4 nested cells inside of the cell array.
% - The depth of the cell in the third position of exampleCA is 2,
% because there are 2 nested cells inside of the cell array.
%
% Notes:
% - All nested cells with contain non-empty data of type 'char', 'double'
% or 'logical'.
% - The length of the cell array is guaranteed to be at least 1.
% - The nested cells will always be 1x1, but the data contained in them
% will not always be.
% - All nested cells will have a depth of at least 1.
%
% Hints:
% - You may find the iscell() function helpful in solving this problem.
%
% Test Cases:
% cA1 = {{{'pumpkin pie'}}, {{{{'pi*r^2'}}}}, {'pie are round'}};
% [index1 depth1] = deepestCell(cA1);
% index1 => 2
% depth1 => 4
%
% cA2 = {{{{{{'CS'}}}}}, {{{'1371'}}}, {{{{{{{{'rulez'}}}}}}}}};
% [index2 depth2] = deepestCell(cA2);
% index2 => 3
% depth2 => 8
%
% cA3 = {{{{{[true true true true false]}}}}};
% [index3 depth3] = deepestCell(cA3);
% index3 => 1
% depth3 => 4
%
% ***Note that in the third test case the outer brackets are still
% considered to be cell array brackets and are NOT included in the
% depth!***
Explanation / Answer
function [index depth] = deepestCell(C)
depth=0;
index=1;
d=0;
for i=1:length(C)
tmp=C{i};
d=0;
while(iscell(tmp))
tmp=tmp{1};
d=d+1;
end
if d>depth
depth=d;
index=i;
end
end
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.