Is there a better way to use cellfun with arguments? and is it better than for-loop?

14 ビュー (過去 30 日間)
Hey,
When I use cellfun, with a function that has arguments, I use repmat function to duplicate my arguments. My question is, if there is a better way to do this.
Here is an example
Lets say that I have a cell array of matricies and I want to get the size of dimention 1 in each
%Create a cell array with random values
randVal = @(x) magic(randi(5,2))
cellArr = arrayfun(randVal, ones(10,1),'uniformOutput',false);
%Get the size of the first dimention of each element in the cell aray
sizes = cellfun(@size,cellArr,repmat({1},size(cellArr,1),1));
This is the part that I am asking about:
repmat({1},size(cellArr,1),1)
Is there a better way to do this?
And in general, is this better that using a for-loop ?
  2 件のコメント
Rik
Rik 2021 年 9 月 9 日
How is what you want different from what Steven posted in his answer? It seems to me that is what you need. Using an anonymous function is a better way than replicating data.
ytzhak goussha
ytzhak goussha 2021 年 9 月 9 日
I stand corrected. You are right!
You were right @Rikk, @Steven Lord' s post was right on the mark and I just didn't understand it.
I removed my comment.
Again, thank you all

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

採用された回答

Jan
Jan 2021 年 9 月 8 日
編集済み: Jan 2021 年 9 月 8 日
sizes = cellfun('size', cellArr, 1);
Using the CHAR vector arguments is mentioned in the documentation as "backward compatibility". This calling style is the only one, in which cellfun is faster than a simple loop.
  4 件のコメント
Rik
Rik 2021 年 9 月 8 日
It looks like this should be possible, but your example is too contrived for me to see if this is what you mean:
arg2=1;
cellfun(@(arg1)size(arg1,arg2),cellArr);
I suspect this is what you need, but with size as the example it is hard to tell.
Jan
Jan 2021 年 9 月 8 日
編集済み: Jan 2021 年 9 月 8 日
Rik's argument is important: If the cell contains e.g. strings, the 'size' command (as char vector) will fail.
I prefer loops. cellfun, arrayfun, structfun allow very compact code. But usually they are harder to read and to maintain. I like fast code also, but I've seen to many projects failing due to a too complex design which impedes the debugging. Therefore is prefer dull loops. The KISS style...

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2021 年 9 月 8 日
A = {1:10, magic(5), @sin}
A = 1×3 cell array
{[1 2 3 4 5 6 7 8 9 10]} {5×5 double} {@sin}
cellfun(@(x) size(x, 1), A)
ans = 1×3
1 5 1

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by