How to obtain indices of cell arrays?

조회 수: 1 (최근 30일)
Dandro18048
Dandro18048 2021년 6월 24일
댓글: Dandro18048 2021년 6월 24일
I have dozens of cell arrays like this that are the output of a long 'for' loop. I need to find the first and the last non-zero indices in each row. For example in the case of the sreenshot attached, I would like to get an output of: [1,3] for the first non-zero cell and [1,8] for the last non-zero cell in this specfic row. Obviously, the postion of non-zero cells and empty cells are very different in each iteration of my loop, so of course I wouldn't know beforehand the postions in the array of the results that I'm looking for, as opposite to the case of the screenshot attached.
I have tried using the function 'find', 'any', etc, but I always get the same error: 'The function is not defined for inputs of type 'cell''
Any ideas please?

채택된 답변

millercommamatt
millercommamatt 2021년 6월 24일
There might be an easier way to do this, but it works.
% get the indices of all non-empty cells
[row,col] = find(cellfun(@(x) ~isempty(x),YourCell));
% grab the cell array size
[numrows, numcols] = size(YourCell);
% preallocate
firstcol_index = NaN(numrows,1);
lastcol_index = NaN(numrows,1);
% get the first and last index for each row, leave NaN if all cols empty
for ii = 1:numrows
single_row_col_inds = col(row == ii);
if ~isempty(single_row_col_inds)
firstcol_index(ii) = min(single_row_col_inds);
lastcol_index(ii) = max(single_row_col_inds);
else
continue
end
end
  댓글 수: 1
Dandro18048
Dandro18048 2021년 6월 24일
Great! Thank you! (In case there are easier/quicker methods it would be nice to know just to get better at it)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by