How to simplify this MATLAB code that calls a function on the output of a function on a cell array of double?
I have this piece of code that is working but is kind of cumbersome. It has one argument which is a cell array and in each cel开发者_JS百科l is a vector of double. All vectors have the same size. I need to calls a function on the output of a function on this variable. For example, here I call log() on all members in the double vector, then call sum() to sum everything. In actual code, the number of cells is much bigger. Is there a way to simplify this without using loops? Thanks!
>> cell_of_double{:}
ans =
0.3140
0.7160
0.6925
0.4265
0.8875
0.5785
0.7185
0.3275
0.3030
0.5745
0.7435
0.6930
0.7290
0.5660
0.2750
ans =
0.3620
0.3580
0.4760
0.5560
0.3245
0.3785
0.8805
0.7600
0.7580
0.5435
0.4985
0.5830
0.6155
0.8010
0.6150
>> cell_of_double
cell_of_double =
[15x1 double]
[15x1 double]
>> sum(cellfun(@sum, cellfun(@(x) sum(arrayfun(@log, x)), cell_of_double(:), 'UniformOutput', false)))
ans =
-18.6004
Since the vectors within your cell are all the same size, you can collapse it into a matrix/vector. The way you're doing the operations on each cell is equivalent to doing it on a supervector. So instead of cellfun
, you can do
dummyVector=cell2mat(cell_of_double);
output=sum(log(dummyVector));
精彩评论