필터 지우기
필터 지우기

Sum of elements in cell array

조회 수: 9 (최근 30일)
Chris Dan
Chris Dan 2020년 7월 29일
답변: Sriram Tadavarty 2020년 7월 29일
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에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by