フィルターのクリア

Move empty cell in a row

5 ビュー (過去 30 日間)
Lorenzo Lasagni
Lorenzo Lasagni 2018 年 5 月 11 日
編集済み: Stephen23 2018 年 5 月 11 日
Hello, I've a cell array structured like this:
{1,2,3,4,5,[],[],[];
6,7,8,[],9,10,[],[];
11,12,13,[],[],[],14,15}
I would like to move the empty cell at the end of the row to eliminate the column after and have only 5 columns and no more 8. How can I do?
Thanks a lot, Lorenzo

採用された回答

Guillaume
Guillaume 2018 年 5 月 11 日
Another option, which may or may not be faster than Rik's (I haven't tested but I suspect it's faster since it doesn't do any sorting:
C = {1,2,3,4,5,[],[],[];
6,7,8,[],9,10,[],[];
11,12,13,[],[],[],14,15}
newC = C'; %tranpose since matlab works by column
newC = newC(~cellfun(@isempty, newC)); %remove all empty cells
newC = reshape(newC, [], size(C, 1))'
This assumes that there is the same number of empty cells in each row.
  2 件のコメント
Rik
Rik 2018 年 5 月 11 日
This is faster by about a factor of 2 (at least for this example on my machine, your mileage may vary).
So if you are certain this condition is true, use this code, if not, use mine. You could of course put it in a try-catch block.
Lorenzo Lasagni
Lorenzo Lasagni 2018 年 5 月 11 日
編集済み: Stephen23 2018 年 5 月 11 日
They are both working well, but yes actually this is faster, thanks both.

サインインしてコメントする。

その他の回答 (1 件)

Rik
Rik 2018 年 5 月 11 日
編集済み: Rik 2018 年 5 月 11 日
Does cell2mat work for you? I you want to keep it as a cell, you can also follow it up with num2cell.
A={1,2,3,4,5,[],[],[];
6,7,8,[],9,10,[],[];
11,12,13,[],[],[],14,15};
B1=cell2mat(A);
B2=num2cell(cell2mat(A));
In cases where each non-empty cell contains arrays, or different data types, the code below can be used, although there might be a more elegant/faster method.
A={1,2,3,4,5,[],[],[];
6,7,8,[],9,10,[],[];
11,12,13,[],[],[],14,15};
for row=1:size(A,1)
temp=A(row,:);
bin=cellfun('isempty',temp);%much faster than @isempty
[~,order]=sort(bin);%sort the empty cells to the back
A(row,:)=A(row,order);%might be a few ms faster than A(row,:)=temp(order);
end
%remove all completely empty columns
A(:,all(cellfun('isempty',A),1))=[];
  2 件のコメント
Lorenzo Lasagni
Lorenzo Lasagni 2018 年 5 月 11 日
I think it wouldn't work because I don't have really a number, but 1==178x3 double or 7 is 5558x3 double
Rik
Rik 2018 年 5 月 11 日
My edit should work for you. If it doesn't, please let me know.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by