Effacer les filtres
Effacer les filtres

Sum of elements in cell array

9 vues (au cours des 30 derniers jours)
Chris Dan
Chris Dan le 29 Juil 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 commentaires
KSSV
KSSV le 29 Juil 2020
Your each cell has 2*3 complex matrix....what you want to add in there?
Chris Dan
Chris Dan le 29 Juil 2020
I want to add all the columns of the matrix and then take the absolute value of them

Connectez-vous pour commenter.

Réponse acceptée

Sriram Tadavarty
Sriram Tadavarty le 29 Juil 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

Plus de réponses (1)

KSSV
KSSV le 29 Juil 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 commentaires
Chris Dan
Chris Dan le 29 Juil 2020
Modifié(e) : Chris Dan le 29 Juil 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 le 29 Juil 2020
It should be
-2999.9805
2126.49999

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by