How to convert all array values into negative ones?
    23 次查看(过去 30 天)
  
       显示 更早的评论
    
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!
0 个评论
采纳的回答
更多回答(3 个)
  Walter Roberson
      
      
 2022-1-31
        A = [2; 3; 5; -8; 9; 1; -1]
%way #1
A(A>0) = -A(A>0)
%way #2
A = [2; 3; 5; -8; 9; 1; -1]
A = -abs(A)
0 个评论
  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]
B = -abs(A) % this makes all of the signs positive, then negates the entire lot 
Or we could do this:
C = -sign(A).*A % this is similar to the use of abs
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)
0 个评论
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!





