How to avoid adding same elements
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Dyuman Joshi
2022-9-21
编辑:Dyuman Joshi
2022-9-21
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')
%using 'stable' to give an idea about the order
%you can use unique without 'stable' option as well
s=sum(b)
sum(unique(a)) and sum(unique(a,'stable')) won't give the same answer.
3 个评论
Dyuman Joshi
2022-9-21
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!