Effacer les filtres
Effacer les filtres

How can I count the sum of inverse value of each non zero elements of a matrix?

17 vues (au cours des 30 derniers jours)
Suppose,
x=[2 1 0 0
0 1 1 1
0 1 1 1
1 0 3 1]
How can I count the sum of inverse value of each non zero elements?
The answer would be = sum (1/2 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/3 + 1/1) = 9.83
How can I count the sum of inverse value of each non zero elements when x also contains NaN?
e.g.,
x=[2 1 0 NaN
0 1 1 1
0 1 1 1
1 0 3 1]

Réponse acceptée

Image Analyst
Image Analyst le 20 Fév 2022
Modifié(e) : Image Analyst le 20 Fév 2022
x=[2 1 0 0
0 1 1 1
0 1 1 1
1 0 3 1]
x = 4×4
2 1 0 0 0 1 1 1 0 1 1 1 1 0 3 1
numNonZeros = nnz(x)
numNonZeros = 11
Not sure what you want for the second question since your sum does not include all 16 elements.
x2=x;
x2(x==0) = 1
x2 = 4×4
2 1 1 1 1 1 1 1 1 1 1 1 1 1 3 1
s = sum(1./x2(:))
s = 14.8333
% Sum 11 of the 16 -- only some of them for some reason.
% Not sure which to take and which to exclude.
thesum = (1/2 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/3 + 1/1) % 11 of the 16
thesum = 9.8333
% Now sum all 16
thesum = (1/2 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/3 + 1/1)
thesum = 14.8333
If this is your homework, you're most likely not allowed to turn my code in as your own. And please tag it as homework if it is.
Regarding your edit, to sum up only elements where x is not zero:
x2=x(:); % Make a copy as a column vector.
x2(x==0) = [] % Remove the zeros.
x2 = 11×1
2 1 1 1 1 1 1 3 1 1
s = sum(1./x2(:))
s = 9.8333
  3 commentaires
Md. Asadujjaman
Md. Asadujjaman le 20 Fév 2022
Modifié(e) : Md. Asadujjaman le 20 Fév 2022
I want to do the following sum:
thesum = (1/2 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/1 + 1/3 + 1/1) = 9.8333
% 11 (non zero elements) of the 16
Note: This is not my homework.
I got my answer. Thank you.
Image Analyst
Image Analyst le 20 Fév 2022
Modifié(e) : Image Analyst le 20 Fév 2022
OK, thanks for Accepting. If you have a newer version of MATLAB you can use the 'omitnan' option like Matt showed below.

Connectez-vous pour commenter.

Plus de réponses (2)

Matt J
Matt J le 20 Fév 2022
sum(1./nonzeros(x),'omitnan')

Jan
Jan le 20 Fév 2022
x = [2 1 0 0; ...
0 1 1 1; ...
0 1 1 1; ...
1 0 3 1];
r = sum(1 ./ x(x ~= 0))
r = 9.8333
x = [2 1 0 NaN; ...
0 1 1 1; ...
0 1 1 1; ...
1 0 3 1];
r = sum(1 ./ x(x ~= 0 & ~isnan(x)))
r = 9.8333

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by