![]() |
在MATLAB中将cell2mat之前的空单元格替换为逻辑0
我有一个空单元格数组,我想将其转换为逻辑数组,其中空单元格为零。当我使用cell2mat时,将忽略空单元格,最后得到的矩阵只有1,而没有引用它们所保存的先前索引。有没有一种方法可以在不使用循环的情况下执行此操作?
示例代码: for n=1:5 %generate sample cell array mycellarray{n}=1; end mycellarray{2}=[] %remove one value for testing 我尝试过的事情: mylogicalarray=logical(cell2mat(mycellarray)); 结果为[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)); 可以,但是使用循环。 [B]回答:[/B] 如果知道单元格数组[I]仅[/I]包含一个和[] (代表零),则可以使用[URL="https://www.mathworks.com/help/matlab/ref/cellfun.html"]cellfun[/URL]函数获取空单元格的逻辑索引,然后取反索引向量: mylogicalarray = ~cellfun(@isempty, mycellarray); % Or the faster option (see comments)... mylogicalarray = ~cellfun('isempty', mycellarray); 如果您的单元格仍然[I]可以[/I]包含零值(而不仅仅是[] ),则可以通过首先使用[URL="https://www.mathworks.com/help/matlab/ref/cellfun.html"]cellfun[/URL]函数查找空单元格的索引来用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 [url=https://stackoverflow.com/questions/2624016]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 05:01。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.