How can I find the length of a cell array in a particular dimension excluding 0x0 doubles?
23 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
As a simple example, say I had this cell array:
examplecell =
{'Name1'} {'Heights'} {'Weights'} {[20000]} {[365]} {[7]}
{'Name2'} {'Heights'} {0x0 double} {0x0 double} {0x0 double} {0x0 double}
{'Name3'} {0x0 double} {0x0 double} {0x0 double} {0x0 double} {0x0 double}
In this 2-D array, I would want to find the number of elements in a specific row which are not {0x0 double}. It is important that the output is for the particular row, not the cell array overall e.g. for the first row the result would be 6, but for the second row it would be 2, and for the third it would be 1. In practice, the cell array is 6-D.
0 Commenti
Risposta accettata
Rik
il 17 Ago 2018
Modificato: Rik
il 13 Gen 2021
You can use ~cellfun('isempty',examplecell) to find out if cells are non-empty, and then you can use sum (specifying a dimension) to count the number of non-empty cells in a particular dimension.
Edit:
This method is much faster than cellfun(@isempty,___), but it doesn't work for classes where isempty is overloaded. At least the string, table, and datetime classes are such examples, but there may be more.
examplecell = [{'Name1'} {'Heights'} {'Weights'} {[20000]} {[365]} {[7]};{'Name2'} {'Heights'} {[]} {[]} {[]} {[]};{'Name3'} {[]} {[]} {[]} {[]} {[]}]
fprintf('char syntax takes %.2f microseconds\n',1000*1000*timeit(@() ~cellfun('isempty',examplecell)))
fprintf('handle syntax takes %.2f microseconds\n',1000*1000*timeit(@() ~cellfun(@isempty,examplecell)))
(on my machine the difference is even larger: 2 vs 9)
5 Commenti
Jingrui Ge
il 13 Gen 2021
Thanks for both of your inputs, now it works perfectly! I have no idea if it's a bug though...
Rik
il 13 Gen 2021
Modificato: Rik
il 15 Gen 2021
I have now reported it as a bug, so we'll see what Mathworks thinks.
Update:
Since string has an overloaded isempty method this behavior is expected. I could not find where this is documented (which('isempty','-all') did suggest something is different). Support forwarded my service request to the documentation people, so they should now be aware.
% NB: the timings seem to have a larger spread than on a local machine
% it took 3 tries to get time reduction figures that make sense
cellfun_consistency_checker
% (the timetable (which fails), cell, and struct lines seem to be cropped)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!