0

The following (nested) function/s

function hpf_matrix {
 # Positional Parameters
 Matrix_Dimension="${1}"
 Center_Cell_Value="${2}"
 # Define the cell value(s)
 function hpf_cell_value {
 if (( "${Row}" == "${Col}" )) && (( "${Col}" == `echo "( ${Matrix_Dimension} + 1 ) / 2" | bc` ))
 then echo "${Center_Cell_Value} "
 else echo "-1 "
 fi
 }
 # Construct the Row for Cols 1 to "Matrix_Dimension"
 function hpf_row {
 for Col in `seq ${Matrix_Dimension}`
 do echo -n "$(hpf_cell_value)"
 done
 }
 # Construct the Matrix
 echo "MATRIX ${Matrix_Dimension}"
 for Row in `seq ${Matrix_Dimension}`
 do echo "$(hpf_row)"
 done
 echo "DIVISOR 1"
 echo "TYPE P"
}

work/s fine, both as a standalone code and inside a script. I.e. hpf_matrix 5 18 will return

MATRIX 5
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 18 -1 -1 
-1 -1 -1 -1 -1 
-1 -1 -1 -1 -1 
DIVISOR 1
TYPE P

and it will even work (with various values) as requested in:

Kernel_Size=5
Center_Cell_Default=18 ; Center_Level=Default
eval Center_Cell="Center_Cell_${Center_Level}"
HPF_MATRIX_ASCII=`hpf_matrix ${Kernel_Size} ${!Center_Cell}`
echo "${HPF_MATRIX_ASCII}"

However, integrating without any changes the above pieces of code (the hpf_matrix function and feeding the "${HPF_MATRIX_ASCII}") inside a larger bash script, errors-out with the following message:

((: 1
2
3
4
5 == 1
2
3
4
5 : syntax error in expression (error token is "2
3
4
5 == 1
2
3
4
5 ")

Minor Update

If I understand correctly, for whatsoever is the reason behind, the line

for Row in seq ${Matrix_Dimension}

as well as the line

for Col in seq ${Matrix_Dimension}

are printed as "1 2 3 4 5" instead of "1" "2" "3" "4" "5".

What is wrong in this case? I would like to keep a nested structure for the function unless it is clearly wrong.

asked Nov 4, 2013 at 15:20
3
  • @user528025 Using your one-liner I ended up to the function mentioned in this question. Thank you. Commented Nov 4, 2013 at 15:27
  • Perhaps related to this: stackoverflow.com/q/6724056/1172302 ? Commented Nov 4, 2013 at 20:12
  • Problem resolved! It was the IFS=, instructed somewhere in the large script. This was messing things up, as well explained at: unix.stackexchange.com/a/88259/13011 Commented Nov 4, 2013 at 20:49

1 Answer 1

1

In the large script, in which the above function was integrated to work as part of it, and prior of defining the hpf_matrix function, the IFS has been changed to IFS=, without taking care to reset it back before using the unquoted command substitution in the function!

An explanation on Using unquoted command substitution ($(...)) without setting $IFS here: https://unix.stackexchange.com/a/88259/13011.

A solution to this also here: https://unix.stackexchange.com/a/92188/13011.

answered Nov 4, 2013 at 20:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.