Filter löschen
Filter löschen

Sum of elements in cell array

9 Ansichten (letzte 30 Tage)
Chris Dan
Chris Dan am 29 Jul. 2020
Beantwortet: Sriram Tadavarty am 29 Jul. 2020
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 Kommentare
KSSV
KSSV am 29 Jul. 2020
Your each cell has 2*3 complex matrix....what you want to add in there?
Chris Dan
Chris Dan am 29 Jul. 2020
I want to add all the columns of the matrix and then take the absolute value of them

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Weitere Antworten (1)

KSSV
KSSV am 29 Jul. 2020
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 Kommentare
Chris Dan
Chris Dan am 29 Jul. 2020
Bearbeitet: Chris Dan am 29 Jul. 2020
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 am 29 Jul. 2020
It should be
-2999.9805
2126.49999

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by