Search code examples
kdb

given the 10x10 matrix m:(10 10)#100?1f In kdb/q


given the 10x10 matrix m:(10 10)#100?1

  1. Find the average of every row and column of the matrix
  2. Find the average of the matrix
  3. Take the first element from the first row, the second from the second row etc
  4. find the diagonal elements of a matrix

Solution

  • First I'm going to change the input so you can better see the solution. The 100?1 will give a list of 100 0s which I don't think is what you want. Maybe you wanted either 100 random (0;1) or 100 random values between 0-1. I went for the latter.

    q)show m:(10 10)#100?1.
    0.4655548 0.8455166  0.7281041 0.7403385 0.5199511  0.199172  0.9548708 0.498..
    0.86544   0.3112134  0.3520122 0.4485896 0.6742543  0.2357538 0.7589261 0.318..
    0.7053699 0.8153197  0.5051956 0.7546554 0.08613905 0.7824787 0.2080171 0.282..
    

    So, now the questions. Find the average of every row and column of the matrix.

    q)meanRows:avg each m
    q)meanCols:avg each flip m
    

    UPDATE From Comment. You can get the average of a matrix column without using each or flip but will return null if any element is null. Another note is that if a column is length 10, 5 of which are null. Then the avg will only consider the average of the 5 non-null values. So, if you believe there are nulls you may want to get rid of them and then get the mean values:

    q)m:^[0;m] //Replace null with 0s if necessary
    q)meanCols:avg m //Get avg without flipping or using each
    

    Find the average of the matrix

    q)avg avg each m
    

    I think that^ is the quickest way to get the overall mean because it doesn't require razing or flipping.

    Take the first element from the first row, the second from the second row etc

    q)getVector:{[mtx]mtx'[c;c:til count mtx]}
    q)getVector m
    0.4655548 0.3112134 0.5051956 0.6333324 0.7258795 0.8671843 0.7556175 0.17954..
    

    Let me know if you have any further questions.