How to convert all array values into negative ones?

조회 수: 77 (최근 30일)
Lu Da Silva
Lu Da Silva 2022년 1월 31일
편집: John D'Errico 2022년 1월 31일
I have an array A:
A = [2; 3; 5; -8; 9; 1; -1]
how do I convert it into an array whose values are all negative? So as to obtain B:
A = [-2; -3; -5; -8; -9; -1; -1]
Thanks!

채택된 답변

KSSV
KSSV 2022년 1월 31일
A = [2; 3; 5; -8; 9; 1; -1] ;
A(A>0) = -A(A>0)
A = 7×1
-2 -3 -5 -8 -9 -1 -1

추가 답변 (3개)

Burhan Burak AKMAN
Burhan Burak AKMAN 2022년 1월 31일
You can do like.
A = [2; 3; 5; -8; 9; 1; -1];
A = -(A.*A).^0.5;
A = 7×1
-2 -3 -5 -8 -9 -1 -1

Walter Roberson
Walter Roberson 2022년 1월 31일
A = [2; 3; 5; -8; 9; 1; -1]
A = 7×1
2 3 5 -8 9 1 -1
%way #1
A(A>0) = -A(A>0)
A = 7×1
-2 -3 -5 -8 -9 -1 -1
%way #2
A = [2; 3; 5; -8; 9; 1; -1]
A = 7×1
2 3 5 -8 9 1 -1
A = -abs(A)
A = 7×1
-2 -3 -5 -8 -9 -1 -1

John D'Errico
John D'Errico 2022년 1월 31일
편집: John D'Errico 2022년 1월 31일
So many ways. Don't forget the simple solution:
A = [2; 3; 5; -8; 9; 1; -1]
A = 7×1
2 3 5 -8 9 1 -1
B = -abs(A) % this makes all of the signs positive, then negates the entire lot
B = 7×1
-2 -3 -5 -8 -9 -1 -1
Or we could do this:
C = -sign(A).*A % this is similar to the use of abs
C = 7×1
-2 -3 -5 -8 -9 -1 -1
Those ways act on the entire array. In order to act only on those that have the wrong sign and do it effectively in place, the standard MATLAB solution would be this:
A(A > 0) = -A(A > 0)
A = 7×1
-2 -3 -5 -8 -9 -1 -1

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by