MATLAB: Sum of elements in cell array

cell arraycell arraysfor loopMATLABmatrix arraysum

Hi,
I have this cell array
One of its rows, look like this
I am using this code to sum the columns of each cell
Force = cellfun(@(x){sum(x(1:3:end,:)); sum(x(2:3:end,:))}, Numerical, 'Uni',0);
But I am not getting correct result , because when I add them manually, I get this ( only for the first row of Numerical{4,1} )
ans =
0.0000e+00 - 1.0232e-12i
But I am getting this( only for the first row of Numerical{4,1} ) :
-1.13686837721616e-13 - 2.27373675443232e-13i
I am attaching the file with the question.
Does anyone know…?

Best Answer

Hi Hamzah,
The issue you observe in numerical values is due to the precision that is not observed for the values.
When the format long is used, you can see what the actual values are. The decimal points up to 15 digits provide the precise results in MATLAB.
You can observe the values you calculated if you round the values to 2 decimal digits. Also, the code you are trying is to sum over the rows, rather than columns.
Implies, for all the expected output, perform as such:
cellfun(@(x) sum(round(x,2),2),Numerical,'UniformOutput',false) % If you replace the round(x,2) directly with x, it is same as you are doing
Hope this helps.
Regards,
Sriram
Related Question