MATLAB: How to manipulate arrays inside a cell array

arrayscellcell array manipulationcell arraysMATLABmultidimensional arrays

Hi,
I have a cell array(1×316) which contains 316 double numeric arrays of various sizes like
{74845×2 double}, {81032×2 double}, {87351×2 double},…..
sample of one array inside the cell-array :
{74845x2}=
0.194 0.0043
0.116 0.0040
0.118 0.0041
0 0.0044
0 0.0037
0 0.0042
0.045 0.0041
0.151 0.0043
0
0.231 0.0040
0
.....................
.....................
Now, Steps to be taken: 1)
Check if the first column values are non-zero,if it is true then, find difference of elements in first and second column separately.
EDIT
There are two cases here:
case i)If there are more than one non-zero elements together in first column then,
find the maximum and minimum values in the group and compute difference as (max-min).
d11 = 0.194(max among 0.118, 0.116, 0.194)- 0.116(Min value of those)
d12 = 0.0043(max among 0.0041, 0.0040, 0.0043)- 0.0040(min of those)
d21 = 0.151-0.045 d22 = 0.0043-0.0041
case ii)If there is only one non-zero element in the first column, no need to take difference.The output should be same.
d31 = 0.231 d32 = 0.0040
2)At last, remove all the zero values from all arrays in the cell.
This way, i need to compute differences among non-zero elements from all the 316 arrays in the cell array and save the results in a new cell array of original size 1×316.
Please help me out on this.
Thanks in advance!

Best Answer

Perhaps you should try something like this:
X = cellfun(@(m)m(:,1)>0,C,'UniformOutput',false);
D = cellfun(@(m,x)abs(diff(m(x,:),1,1)),C,X,'UniformOutput',false);
(It could be done in one cellfun call, but this clearly separates the logical condition and the diff operation).
EDIT to place the values into groups (based on non-zero values in the first column), and then calculate the max and min of each group:
M = [0.194,0.0043;0.116,0.0040;0,0.0044;0,0.0037;0,0.0042;0.045,0.0041;0.151,0.0043;0.231,0.0040;0.106,0.0043;0,0.0040];
C = {M};
% Preallocate an output cell array:
D = cell(numel(C),2);
for k = 1:numel(C)
% locate non-zero values in first column:
idx = 0<C{k}(:,1);
% number those values according to each group:
idg = cumsum(0<diff([false;idx]));
% get max and min of each group, for 1st and 2nd column:
mx1 = accumarray(idg(idx),C{k}(idx,1),[],@max);
mx2 = accumarray(idg(idx),C{k}(idx,2),[],@max);
mn1 = accumarray(idg(idx),C{k}(idx,1),[],@min);
mn2 = accumarray(idg(idx),C{k}(idx,2),[],@min);
% calculate difference of max and min:
D{k,1} = mx1-mn1;
D{k,2} = mx2-mn2;
end