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.

 채택된 답변

Dyuman Joshi
Dyuman Joshi 2022년 9월 21일
편집: Dyuman Joshi 2022년 9월 21일

0 개 추천

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

If you turn out to be working only with integers, and your sum will not exceed 9007199254740992 then you can use
sum(unique(a))
without the 'stable' option.
However if you have fractions such as [.1 .2 .3] then the order of summation can make a difference to the last few bits of the final result.
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 2022년 9월 21일
Thank you very much for your help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

질문:

2022년 9월 21일

편집:

2022년 9월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by