logo
down
shadow

Apply function to each submatrix


Apply function to each submatrix

By : Ermir Bajraktari
Date : November 21 2020, 01:01 AM
will help you Here is a way. It assumes the function being applied returns a scalar, like it is the case with mean:
code :
A <- matrix(1:16, 4, 4)
k <- 2L

i <- (row(A) + 1L) %/% k        # row grouping
j <- (col(A) + 1L) %/% k        # col grouping
b <- i + (j - 1L) * max(i)      # block grouping
#      [,1] [,2] [,3] [,4]
# [1,]    1    1    3    3
# [2,]    1    1    3    3
# [3,]    2    2    4    4
# [4,]    2    2    4    4

subA <- split(A, b)             # sub-matrices
subm <- sapply(subA, mean)      # sub-means
out  <- array(subm[b], dim(A))  # final output
#      [,1] [,2] [,3] [,4]
# [1,]  3.5  3.5 11.5 11.5
# [2,]  3.5  3.5 11.5 11.5
# [3,]  5.5  5.5 13.5 13.5
# [4,]  5.5  5.5 13.5 13.5


Share : facebook icon twitter icon
return reference to a submatrix from function in numpy

return reference to a submatrix from function in numpy


By : Ia Pereira
Date : March 29 2020, 07:55 AM
To fix the issue you can do how I can ... pass reference to the submatrix out of function?
Simply put, you cannot return an l-value from a function call in Python like you can in C++. In your case, Python assumes that you are assigning a value directly to the sub(a), which is a function call, and not to the object returned by it.
code :
def sub(a):
    a[:2, :2] = np.arange(4).reshape((2,2))
    return a[:2, :2]
>>> x = sub(a)
>>> x[:] = np.ones((2,2))
>>> x
array([[1, 1],
       [1, 1]])
>>> a
array([[1, 1, 2],
       [1, 1, 5],
       [6, 7, 8]])
>>> sub(a)[:] = np.ones((2,2))
>>> a
array([[1, 1, 2],
       [1, 1, 5],
       [6, 7, 8]])
>>> x = 2         # this won't change a because x is a reference passed by value
>>> a
array([[1, 1, 2],
       [1, 1, 5],
       [6, 7, 8]])
Armadillo C++: Passing a submatrix into a function

Armadillo C++: Passing a submatrix into a function


By : user2977895
Date : March 29 2020, 07:55 AM
This might help you Change the input type to a const reference (const arma::mat&), which allows the compiler to automatically generate a temporary matrix in such cases.
Example:
code :
using namespace arma;

mat foo(const mat& my_matrix)
{
  mat y = my_matrix * 2.0;

  return y;
}


void bar()
{
  mat x(10,10, fill::randu);

  mat y = foo( x.col(0) );

  y.print("y:");
}
R apply Return submatrix

R apply Return submatrix


By : user3079203
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Given this code: , You can try
code :
do.call(`c`,apply(splitData, 1, function(x) list(test[x,])))
lapply(seq_len(nrow(splitData)), function(i)  test[unlist(splitData[i,]),])
Get dynamic submatrix and apply constraints

Get dynamic submatrix and apply constraints


By : LiwaeL
Date : March 29 2020, 07:55 AM
I wish this help you The way to get a value from an array based on an IntVar, inside the solver, is by using the MakeElement() function and in this case the 2d version of it.
That way you can get a specific value from the matrix but not a range based on two IntVars (for example x - dx of rectangles). To accomplish the range part you can use a loop and a ConditionalExpression() to figure out if the specified value is in range.
code :
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
IntVar x = solver.MakeIntVar(0, data.Length - 1);
IntVar dx = solver.MakeIntVar(1, data.Length);

solver.Add(x + dx <= data.Length);

IntVarVector range = new IntVarVector();
for (int i = 0; i < dx.Max(); i++)
{
    range.Add(solver.MakeConditionalExpression((x + i < x + dx).Var() , solver.MakeElement(data, (x + i).Var()), 0).Var());
}

solver.Add(range.ToArray().Sum() <= 10);
class DataValues: LongLongToLong
{
    private int[,] _data;
    private int _rows;
    private int _cols;

    public DataValues(int[,] data, int rows, int cols)
    {
        _rows = rows;
        _cols = cols;
        _data = data;
    }

    public override long Run(long arg0, long arg1)
    {
        if (arg0 >= _rows || arg1 >= _cols)
            return 0;

        return _data[arg0, arg1];
    }
}
How to pass submatrix to another function as a pointer

How to pass submatrix to another function as a pointer


By : swoo0day
Date : March 29 2020, 07:55 AM
will be helpful for those in need You cannot do this using only pointer arithmetic. What you have is an array of arrays. Assuming outer array holds rows and inner arrays hold the elements (columns) of each row, you can pass a pointer to the middle of the outer array to skip rows but you cannot skip columns. If you need to skip columns as well you have two options:
code :
elem **get_submatrix(elem **mat, int n, int x, int y, int m)
{
   elem **submat = (elem **)calloc(m, sizeof(elem*));
   int i;
   for(i = 0; i < m; i++)
   {
       submat[i] = mat[y++] + x;
   }
   return submat;
}
Related Posts Related Posts :
  • Re coding in R using complicated statement
  • accumulating functions and closures in R
  • How do you combine two columns into a new column in a dataframe made of two or more different csv files?
  • Twitter authentication fails
  • Summing Values of One Vector Conditional on Values of Another Vector
  • draw cube into 3D scatterplot in RGL
  • lme4 translate formula to code in 3-level model
  • How to draw single axis plot in R
  • Combine geom_tile() and facet_grid/facet_wrap and remove space between tiles (ggplot2)
  • Use snpStats with R version 3.0.1
  • Makefile gives strange error while compiling markdown file into .docx file
  • How to determine whether a points lies in an ellipse
  • Summarize data already grouped in r
  • Is the bigvis package for R not available for R version 3.0.1?
  • Operator overloading in R reference classes
  • How to enable user to switch between ggplot2 and gVis graphs in R Shiny?
  • Is there an easy way to separate categorical vs continuous variables into two dataset in R
  • Correct previous year by id within R
  • Installation of rdyncall package for R
  • ggplot2 plot that evaluates the percentage and mean of a third variable at intersecting points
  • Error Handling with Lapply
  • data.table - split multiple columns
  • How to compute the overall mean for several files in R?
  • R: Graph Plotting: Subscripts in the legend like LaTeX
  • Restructuring data in R
  • Distance of pointsfrom cluster centers after K means clustering
  • R incorrect value of date function
  • Package "Imports" not loading in R development package
  • r - run a user defined function several times by taking column elements as parameters
  • Create input$selection to subset data AND radiobuttons to choose plot type in Shiny
  • Generate crosstabulations from dataframe of categorical variables in survey
  • Restructure output of R summary function
  • New behavior in data.table? .N / something with `by` (calculate proportion)
  • search certain number vector in R
  • R version doesn't support quartz graphic device - RStudio won't plot
  • Referencing a function parameter in R
  • How to synchronize signals using a cross-correlation and FFT in R?
  • Plotting coefficients and corresponding confidence intervals
  • passing expressions to curve() within a function
  • More effective merging of matched column with duplicates in data.table
  • Easy way to export multiple data.frame to multiple Excel worksheets
  • R Foreach Iterator - Walkforward
  • Table format and output in R
  • Restructuring data and duplicating rows in R
  • use ggplot2 to plot two lines with ribbons
  • how to plot a graph on lattice with two different colors
  • How can I keep a date formatted in R using sqldf?
  • Generating simulation data based on a specified distribution
  • Joining list of data frames in R
  • Subset data in R
  • R: How to avoid 2 'for' loops in R in this function
  • + signs appearing in console in R
  • how to create a dataframe form a lists within a list in R
  • Best way to combine and keep columns
  • Using identify and attach in a function
  • How to assign regular strings for quarterly and monthly observation labels to the row names of a data frame?
  • Adjust hexbin legend breaks
  • Different lowess curves in plot and qplot in R
  • Extract words only with R
  • switch case: several equivalent cases expressions in r
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org