2

How can I find the maximum element and its index from an array in shell script. I have an array

a = [-2.2116565098 -2.1238242060 -2.1747941240 -2.3201010162 -2.3677779871 -1.8126464132 -2.1247209755 -2.1190930712 -2.3242384636 -2.1081702064];

Now, I want to find the maximum as well as its index in bash script. Is there a shortcut like in Matlab we have

[C, I] = max(a);

Also, also how can we have multi-dimensional array and get the index and value of minimum and maximum element.

2 Answers 2

2
$ x='-2.2116565098 -2.1238242060 -2.1747941240 -2.3201010162 -2.3677779871'
$ IC=(`tr ' ' '\n' <<<$x | cat -n | sort -k2,2nr | head -n1`)
$ I=${IC[0]} C=${IC[1]}
$ echo $I $C
2 -2.1238242060
Sign up to request clarification or add additional context in comments.

2 Comments

The above code works for me on my computer. But strangely, when I run it on a remote computer it just returns the first index and value of the first element. What do you think could explain this?
I always get the first index value, but a different element. For example, if I have x='19 21 23', I will get $I as 23 but $C as 1, even though it's clearly element 3.
0

Shell scripts in general do not support arrays at all, so what you are asking for is impossible. I am not aware of any shells that support multi-dimensional arrays, but some shells do provide minimal support for one dimensional arrays. Some of those shells probably provide convenient ways to perform the operations you need. To find the maximum value and the index in bash, which is one particular shell that does provide primitive support for arrays, you will need to loop over the array (as far as I know). However, bash does not provide good support for floating point values, so before you implement this, you should consider using a different language. Here is an example of one method:

idx=0
maxidx=0
max=${a[0]}
for v in ${a[@]}; do
    expr $v \> $max > /dev/null && { maxidx=$idx; max=$v; }
    : $((idx++))
done

There may be better techniques within bash for accessing the array, but it is generally a bad idea IMO to use shell specific constructs. If you are going to be using sh, even arrays really ought to be avoided, because not all shells support them. If you want to use a language feature of a non-standard shell, you might as well use perl, python, ruby, or your language of choice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.