Sum of elements in cell array

15 次查看(过去 30 天)
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...?
  2 个评论
KSSV
KSSV 2020-7-29
Your each cell has 2*3 complex matrix....what you want to add in there?
Chris Dan
Chris Dan 2020-7-29
I want to add all the columns of the matrix and then take the absolute value of them

请先登录,再进行评论。

采纳的回答

Sriram Tadavarty
Sriram Tadavarty 2020-7-29
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

更多回答(1 个)

KSSV
KSSV 2020-7-29
Better use loop to avoid confusion using cellfun. Note cellfun also use loop inside.
clc; clear all ;
load("numerical.mat");
[m,n] = size(Numerical) ;
iwant = cell(m,1) ;
for i = 1:m
iwant{i} = abs(sum(Numerical{i})) ;
end
  2 个评论
Chris Dan
Chris Dan 2020-7-29
编辑:Chris Dan 2020-7-29
This code is giving wrong answers...
one of the cells ( Numerical{3,1} is this
and the answer which I am getting from the code is
It is not correct.
Can you please look into it.
Chris Dan
Chris Dan 2020-7-29
It should be
-2999.9805
2126.49999

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by