Dor*_*oom 17 matlab matrix cell-array is-empty
我有一个空单元格数组和一些我想要转换为逻辑数组的单元格,其中空单元格为零.当我使用cell2mat时,空单元格被忽略,我最终得到一个只有1的矩阵,没有引用它们持有的先前索引.有没有办法在不使用循环的情况下执行此操作?
示例代码:
for n=1:5 %generate sample cell array
mycellarray{n}=1;
end
mycellarray{2}=[] %remove one value for testing
Run Code Online (Sandbox Code Playgroud)
我试过的事情:
mylogicalarray=logical(cell2mat(mycellarray));
Run Code Online (Sandbox Code Playgroud)
这导致[1,1,1,1],而不是[1,0,1,1,1].
for n=1:length(mycellarray)
if isempty(mycellarray{n})
mycellarray{n}=0;
end
end
mylogicalarray=logical(cell2mat(mycellarray));
Run Code Online (Sandbox Code Playgroud)
哪个有效,但使用循环.
gno*_*ice 28
如果你知道你的单元格数组只包含1和[](代表你的零),你可以使用该函数cellfun获取空单元格的逻辑索引,然后否定索引向量:
mylogicalarray = ~cellfun(@isempty, mycellarray);
% Or the faster option (see comments)...
mylogicalarray = ~cellfun('isempty', mycellarray);
Run Code Online (Sandbox Code Playgroud)
如果您的单元格仍然可以包含零值(不仅仅是[]),则可以首先使用该函数cellfun查找空单元格的索引,将空单元格替换为0 :
emptyIndex = cellfun('isempty', mycellarray); % Find indices of empty cells
mycellarray(emptyIndex) = {0}; % Fill empty cells with 0
mylogicalarray = logical(cell2mat(mycellarray)); % Convert the cell array
Run Code Online (Sandbox Code Playgroud)
mycellarray( cellfun(@isempty, mycellarray) ) = {0};
mylogicalarray = logical(cell2mat(mycellarray));
Run Code Online (Sandbox Code Playgroud)