Effacer les filtres
Effacer les filtres

How to avoid adding same elements

2 vues (au cours des 30 derniers jours)
MIch
MIch le 21 Sep 2022
Modifié(e) : Dyuman Joshi le 21 Sep 2022
Hello,
I have one question.
I need to sum elements of an matrix 1x7, but I need to exclude same elements.
For example
a=[5 4 3 2 1 1 6]
I would like to get b=5+4+3+2+1+6, not 5+4+3+2+1+1+6.

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 21 Sep 2022
Modifié(e) : Dyuman Joshi le 21 Sep 2022
You can use unique to get the elements without repetition (subject to sum being less than 9007199254740992, as mentioned below)
%random data
a=[5 4 5 3 2 6 1 6 1 6];
b=unique(a,'stable')
b = 1×6
5 4 3 2 6 1
%using 'stable' to give an idea about the order
%you can use unique without 'stable' option as well
s=sum(b)
s = 21
Edit - In case you are dealing with fractional number, as @Walter Roberson commented,
sum(unique(a)) and sum(unique(a,'stable')) won't give the same answer.
  3 commentaires
Dyuman Joshi
Dyuman Joshi le 21 Sep 2022
I am aware that one can use unique() without the 'stable' option, I just used stable option to give a hint.
Though you are right about fractions, I will edit my statement in my answer accordingly.
format long e
flintmax
ans =
9.007199254740992e+15
MIch
MIch le 21 Sep 2022
Thank you very much for your help.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by