Compile multiple cells in a single vector including empty cells as zero elements.

조회 수: 1 (최근 30일)
MANISH KUMAR
MANISH KUMAR 2020년 5월 6일
답변: Voss 2023년 12월 14일
I have this as input
H = [] [] [5] [] [3]
and I want
H = [0 0 5 0 3]
as output.
Please help!
  댓글 수: 2
Michael Soskind
Michael Soskind 2020년 5월 6일
I will provide a very naive method here. Maybe someone has a better solution.
H = {[],[],5,[],3}; % original array
for i = 1:size(H,1) % loop through rows (1)
for j = 1:size(H,2) % loop through columns (5)
if isempty(H{i,j})
H{i,j} = [0]; % if empty, replace the empty array with zero
end
end
end
H_new = cell2mat(H) % convert cell to matrix
You could use a temporary cell array if you do not want to modify the original cell array H.

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

답변 (1개)

Voss
Voss 2023년 12월 14일
H = { [] [] [5] [] [3] } % original array
H = 1×5 cell array
{0×0 double} {0×0 double} {[5]} {0×0 double} {[3]}
H(cellfun(@isempty,H)) = {0} % if empty, replace the empty array with zero
H = 1×5 cell array
{[0]} {[0]} {[5]} {[0]} {[3]}
H = [H{:}] % convert cell to matrix
H = 1×5
0 0 5 0 3

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by