MATLAB Answers

0

Trimming Null Characters off a multi-dimensional cell array

Bryce Johnson さんによって質問されました 2019 年 6 月 10 日
最新アクティビティ dpb
さんによって コメントされました 2019 年 6 月 11 日
dpb
さんの 回答が採用されました
I'm trying to trim the null characters off a multi-dimensional cell array that looks like this:
A={'a','b','c'; ----> desired output A={'a','b','c';
't','y',[]; 't','y',[];
[],'z',[]; [],'z',[];}
[],[],[];
[],[],[]}
When I use A(~cellfun('isempty',A)) I end up getting back a colum vector of everything but the null characters. I understand I could probably just use a for loop to find the longest column, then cut it from there, however I may be taking in a lot of data and my code is already quite slow, so I was wondering if there was any elegant/fast solutions to this problem?

  0 件のコメント

サインイン to comment.

1 件の回答

dpb
回答者: dpb
2019 年 6 月 10 日
 採用された回答

>> A(any(~cellfun(@isempty,A),2),:)
ans =
3×3 cell array
{'a' } {'b'} {'c' }
{'t' } {'y'} {0×0 double}
{0×0 double} {'z'} {0×0 double}
>>

  4 件のコメント

Guillaume
2019 年 6 月 11 日
You haven't used the same code that dpb showed, so of course you get a different answer.
cellfun(@isempty, A)
returns a logical array the same size as A indicating which cells are empty
any(X, 2)
reduces a logical array to a column vector which is true if any of the element in the corresponding row is true. Therefore
any(~cellfun(@isempty, A))
is a column vector where each row is true if any of the cell of A on the same row is not empty.
A(logicalvector, :)
selects all the columns (because of the : in the 2nd dimension) of the rows for which the logical vector is true (as the vector is in the first dimension.
On the other hand, what you've written:
A(logicalvector)
uses linear indexing, so in effects flattens A into a vector and select only these elements which for which the logical vector is true. If the logical vector is shorter than the number of elements in A (as is the case with what you've written) the remaining elements are not selected.
Bryce Johnson 2019 年 6 月 11 日
Oh I see now, I tought that was a smiley face for some reason! Thank you for your intuitive explanation it will definelty help me when solving problems like this in the future!
dpb
2019 年 6 月 11 日
Would seem then you're still at the learning level that spending some time working thru the excercises at the Getting Started link in the documentation would pay back many times over on time invested...

サインイン to comment.



Translated by