Home > OS >  Multiply every element of an array by the same scalar in zsh
Multiply every element of an array by the same scalar in zsh

Time:03-02

I would like to multiply every element in an array in zsh by the same scalar. I would be able to do this very easily in Python, but have looked in many places and cannot figure out how to do it in a zsh script.

I would like to write code like

#!/bin/zsh
mean=(1 2 2 1 -1 -2 -2 -1)
echo $((2 * $mean))

But when I try to do this I get the error message

bad math expression: operator expected at `2 2 1 -1 -...'

Any and all help would be appreciated. I can't seem to find anything online that is even remotely close to what I'm trying to figure out how to do.

CodePudding user response:

You have to iterate over the elements of the array and multiply each one:

#!/usr/bin/env zsh
typeset -a mean=(1 2 2 1 -1 -2 -2 -1)
for n in "${mean[@]}"; do
    print $((2 * n))
done

CodePudding user response:

There are some hacky ways to implement a map():

$ set -o extendedglob
$ a=(1 2 2 1 -1 -2 -2 -1)
$ print ${a//(#m)*/$((MATCH * 2))}
2 4 4 2 -2 -4 -4 -2

But a loop is probably the easiest:

$ b=(); for i ($a) b =$((i*2)); print $b
2 4 4 2 -2 -4 -4 -2
  • Related