First of all, if you do not have really large vectors, use a unique one and get the second last index.
If you want to save the max element, and the vector does not contain NaN, you can try:
[max_value,max_idx] = max(A); % [3 5 6 7] A(idx) = NaN; % [3 5 6 NaN] second_max_value = max(A); % 6 A(idx) = max_value; % [3 5 6 7]
If you have multiple indexes with the same maximum value, you can enable
if length(max_idx)>1, second_max_value=max_value, end
UPDATE:
According to the OP comment next to the question, let me add:
You can also use sort without changing the original array:
[~, idx] = sort(A); A(idx(1)) % is the max value A(idx(2)) % is the second max value
source share