Adding Arrays of cells

조회 수: 2 (최근 30일)
Sultan
Sultan 2017년 9월 23일
댓글: Stephen23 2017년 9월 23일
I have ten arrays of 15-dimensional A1, ..., A10 which consist of cells of different size. All arrays have same format i.e., same dimension of cells for all Ai, i=1,..10 respectively.
Ai = [2x1 double] [1x2 double] [2x2 double] [2x1 double] [2x2 double] [2x2 double] [2x2x2 double] [2x1 double] [2x2 double] [2x2 double] [2x2x2 double] [2x2 double] [2x2x2 double] [2x2x2 double] [4-D double]
I want A in same format where A is an array which have the mean of all components of cells of Ai, i =1,...,10. That is, A = (A1+ ... +A10)/10.
Please help me. Thanks :MSA
  댓글 수: 1
Stephen23
Stephen23 2017년 9월 23일
"I have ten arrays of 15-dimensional A1, ..., A10..."
And that is the start of your problem right there. Do not create lots of numbered variables! Simply store your data in one array and your life will be much simpler (and your code faster and less buggy too).
This is what the MATLAB documentation says about your code idea: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
You can read more explanations of the problems caused by accessing variable names dynamically:

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2017년 9월 23일
There is a reason we keep on saying not to create numbered or dynamically named variables. It makes using them extremely difficult.
First step: change your algorithm to create just one variable. Options are a cell array of these cell arrays or concatenating the content of the cells in an extra dimension. Once that's done it's almost trivial to calculate the mean:
A = {A1, A2, ...} %cell array of cell arrays
meanA = cellfun(@(varargin) mean(cat(ndims(varargin{1})+1, varargin{:}), ndims(varargin{1})+1) , A{:}, 'UniformOutput', false)
The complication here is that I don't know the dimensionality of the matrices you want to average. All the cellfun does is concatenate them all in a higher dimension and take the mean in that dimension.
The result of the concatenation without the mean calculation would be the other way to keep your matrices together
A = {A1, A2, ...} %cell array of cell arrays
A = cellfun(@(varargin) cat(ndims(varargin{1})+1, varargin{:}), A{:}, 'UniformOutput', false)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by