find size uniformity in matlab along a cell array

4 ビュー (過去 30 日間)
ludvikjahn
ludvikjahn 2015 年 3 月 5 日
編集済み: Stephen23 2015 年 3 月 9 日
good morning, I have a cell array like:
A= {[1 19 65];[ 5];[8 8 3]; [9 7 43]}
and I want to know if its dimensions are costant along the array (of course in this case the answer should be negative because it is made of 3 [1 x 3] cells and one [1 x 1] cell). Any idea about how to do it without a for loop?
Thanks

回答 (2 件)

Adam
Adam 2015 年 3 月 5 日
dim = size( A{1} );
allDimsSame = all( cellfun( @(x) isequal( size(x), dim ), A ) );
will give you the correct answer, but is likely slower than a simple for loop, especially if you have a vast cell array and the 2nd element differs in size from the first which would terminate a loop immediately after 1 comparison.
  2 件のコメント
ludvikjahn
ludvikjahn 2015 年 3 月 5 日
編集済み: ludvikjahn 2015 年 3 月 5 日
ok, and if i wanted, (even with a for cycle) to cut the cell array when it encounters a different size cell? (in this case it should be cut at the first cell)
or even exclude those cell which do not have tha same size as the first one? Thanks
Adam
Adam 2015 年 3 月 5 日
編集済み: Adam 2015 年 3 月 5 日
allDimsSame = true;
dim = size( A{1} );
for i = 2:numel(A)
if ~isequal( size( A{i} ), dim )
allDimsSame = false;
break;
end
end
should jump out of a for loop as soon as a cell containing a different sized element is found.
If you want to exclude cells of a different size to the first then we should go back to the first answer (or a for loop equivalent of it which is likely still faster even without early termination) with a slight change:
dimsSame = cellfun( @(x) isequal( size(x), dim ), A );
A( ~dimsSame ) = [];
dimsSame is a logical array so everywhere it is 0 the cell contents were a different size so we just replace them with empty which deletes them from the array.
Whatever you do, do not attempt to delete elements from the cell array in the middle of a for loop!

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


Stephen23
Stephen23 2015 年 3 月 5 日
編集済み: Stephen23 2015 年 3 月 9 日
The cellfun options listed under "Backwards Compatibility" are much faster than normal cellfun calls:
>> A = {[1,19,65]; [5]; [8,8,3]; [9,7,43]};
>> any(diff(cellfun('size',A,1))) % check the first dimension
ans = 0
>> any(diff(cellfun('size',A,2))) % check the second dimension
ans = 1
tell us that one of the column sizes is different.
  1 件のコメント
Guillaume
Guillaume 2015 年 3 月 5 日
Yes, isn't it ironic that a deprecated syntax is much more performant than its replacement?

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by