0

What is the correct way of computing the difference between two arrays of the same size and give them to a new array. Given array A and B this does not work: float[] C = A-B.

e.g.:

A = array.new_int(100,-1)
B = array.new_int(100,1)

how to do A-B

sey eeet
  • 229
  • 2
  • 8

1 Answers1

1

You need to loop through the array and subtract the elements one by one.

Below code assumes array sizes are the same so no checks for that.

//@version=5
indicator("My script")

A = array.from(1, 2, 3, 4 ,5)
B = array.from(4, 0, 2, 3, 1)

len_A = array.size(A)
len_B = array.size(B)

C = array.new_int(len_A)

for i=0 to len_A-1
    val_A = array.get(A, i)
    val_B = array.get(B, i)
    array.set(C, i, val_A - val_B)

var testTable = table.new( position.top_right, len_A + 1, 4, color.yellow, border_color=color.black, border_width=1)

if barstate.islast
    table.cell(testTable, 0, 0, "Array")
    table.cell(testTable, 0, 1, "A")
    table.cell(testTable, 0, 2, "B")
    table.cell(testTable, 0, 3, "C")

    row = 0
    col = 1

    for i=0 to len_A-1
        val_A = array.get(A, i)
        val_B = array.get(B, i)
        val_C = array.get(C, i)

        table.cell(testTable, col, row, str.tostring(i))
        table.cell(testTable, col, row+1, str.tostring(val_A))
        table.cell(testTable, col, row+2, str.tostring(val_B))
        table.cell(testTable, col, row+3, str.tostring(val_C))
        col := col + 1

enter image description here

vitruvius
  • 15,740
  • 3
  • 16
  • 26