How do I find absolute max value in a vector without losing the sign when the value is negative in MatLab R2011b?

조회 수: 66 (최근 30일)
I have many vectors that contain force and joint moment data and I need to find the max values without losing the sign. For example, if the values were [2 6 -7] I'd need to get -7, if the vector was [-2 5 6] I'd need to get 6. For certain reasons, I have to work with MatLab R2011b.

채택된 답변

Stephen23
Stephen23 2018년 10월 29일
편집: Stephen23 2018년 10월 29일
Method one: use indexing to select from the original vector:
>> V = [2,6,-7];
>> [~,X] = max(abs(V));
>> V(X)
ans = -7
>> V = [-2,5,6];
>> [~,X] = max(abs(V));
>> V(X)
ans = 6
Method two: use sign to multiply with the output value:
>> V = [2,6,-7];
>> [A,X] = max(abs(V));
>> A.*sign(V(X))
ans = -7
>> V = [-2,5,6];
>> [A,X] = max(abs(V));
>> A.*sign(V(X))
ans = 6
  댓글 수: 3
Stephen23
Stephen23 2021년 2월 4일
It would be nice if max et al would return linear indices. Your indexing is probably about the simplest, but because you hard-code the columns it is not very generalized. Here is a generalized solution:
M = [2,6,-7;-5,2,1;0,-3,9].'
M = 3×3
2 -5 0 6 2 -3 -7 1 9
[~,R] = max(abs(M),[],1);
X = sub2ind(size(M),R,1:size(M,2));
V = M(X)
V = 1×3
-7 -5 9
Steven Lord
Steven Lord 2021년 2월 4일
The max and min functions can return linear indices as of release R2019a.
M = [2,6,-7;-5,2,1;0,-3,9].'
M = 3×3
2 -5 0 6 2 -3 -7 1 9
[~, ind] = max(abs(M), [], 1, 'linear')
ind = 1×3
3 4 9
M(ind)
ans = 1×3
-7 -5 9

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by