logo
down
shadow

How can i build a for function for matrix?


How can i build a for function for matrix?

By : Camila Santos
Date : November 19 2020, 12:41 AM
wish of those help Now i have a list like below: , You don't need a for loop for that. You can use lapply:
code :
## First, make up some sample data
set.seed(1)
mylist <- replicate(2, sample(0:1, 9, TRUE), FALSE)

## Let's work on a copy in case you need the original
m <- mylist 
m
# [[1]]
# [1] 0 0 1 1 0 1 1 1 1
# 
# [[2]]
# [1] 0 0 0 1 0 1 0 1 1

## Here's the actual transformation
m[] <- lapply(m, matrix, nrow = 3, byrow = TRUE)
m
# [[1]]
#      [,1] [,2] [,3]
# [1,]    0    0    1
# [2,]    1    0    1
# [3,]    1    1    1
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    1    0    1
# [3,]    0    1    1


Share : facebook icon twitter icon
Is there a build-in function to create a matrix m such that m(r,c) = fun(r,c)

Is there a build-in function to create a matrix m such that m(r,c) = fun(r,c)


By : mihe
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Just to make it clear, there is no generic "vectorized" solution if fun does not accept vectors (or matrices) for input.
That said, I'll add to nate's answer and say that in case fun does not accept matrices you can go about this with:
code :
[Y, X] = meshgrid(1:R, 1:C);
m = arrayfun(@(r, c)fun(r, c), X, Y)
Vectorize numpy indexing and apply a function to build a matrix

Vectorize numpy indexing and apply a function to build a matrix


By : Cane Corso Puppy
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have a matrix X of size (d,N). In other words, there are N vectors with d dimensions each. For example, , Here's an approach -
code :
# Get a flattened version of indices
idx0 = np.concatenate(I)

# Get indices at which we need to do "intervaled-summation" along axis=1
cut_idx = np.append(0,map(len,I))[:-1].cumsum()

# Finally index into cols of array with flattend indices & perform summation
out = np.add.reduceat(X[:,idx0], cut_idx,axis=1)
In [67]: X
Out[67]: 
array([[ 1,  2,  3,  4],
       [15,  6, 17,  8]])

In [68]: I
Out[68]: array([[0, 2, 3, 1], [2, 3, 1], [2, 3]], dtype=object)

In [69]: idx0 = np.concatenate(I)

In [70]: idx0 # Flattened indices
Out[70]: array([0, 2, 3, 1, 2, 3, 1, 2, 3])

In [71]: cut_idx = np.append(0,map(len,I))[:-1].cumsum()

In [72]: cut_idx # We need to do addition in intervals limited by these indices
Out[72]: array([0, 4, 7])

In [74]: X[:,idx0]  # Select all of the indexed columns
Out[74]: 
array([[ 1,  3,  4,  2,  3,  4,  2,  3,  4],
       [15, 17,  8,  6, 17,  8,  6, 17,  8]])

In [75]: np.add.reduceat(X[:,idx0], cut_idx,axis=1)
Out[75]: 
array([[10,  9,  7],
       [46, 31, 25]])
How to build & store this large lower triangular matrix for matrix-vector multiplication?

How to build & store this large lower triangular matrix for matrix-vector multiplication?


By : wodes
Date : March 29 2020, 07:55 AM
wish helps you You don't always need to explicitly form a matrix to do a matrix-vector or matrix-matrix multiplication. For example, no one really forms a diagonal matrix and use it for such computations.
There is no substantial difference between your matrix and a diagonal matrix.
code :
MatVecMul <- function (y, k) {
  n <- length(y)
  z <- numeric(n)
  for (i in 1:n) z[i:n] <- z[i:n] + k ^ (i - 1) * y[1:(n - i + 1)]
  z
  }
d <- structure(c(1, 0.9, 0.81, 0.729, 0.6561, 0, 1, 0.9, 0.81, 0.729, 
0, 0, 1, 0.9, 0.81, 0, 0, 0, 1, 0.9, 0, 0, 0, 0, 1), .Dim = c(5L, 5L))
set.seed(0); y <- runif(5)
c(d %*% y)
#[1] 0.8966972 1.0725361 1.3374064 1.7765191 2.5070750

MatVecMul(y, 0.9)
#[1] 0.8966972 1.0725361 1.3374064 1.7765191 2.5070750
library(Rcpp)
cppFunction("NumericVector MatVecMul_cpp (NumericVector y, double k) {
  int n = y.size();
  NumericVector z(n);
  int i; double *p1, *p2, *end = &z[n];
  double tmp = 1.0;
  for (i = 0; i < n; i++) {
    for (p1 = &z[i], p2 = &y[0]; p1 < end; p1++, p2++) *p1 += tmp * (*p2);
    tmp *= k;
    }
  return z;
  }")

MatVecMul_cpp(y, 0.9)
#[1] 0.8966972 1.0725361 1.3374064 1.7765191 2.5070750
v <- runif(1e4)
system.time(MatVecMul(y, 0.9))
#   user  system elapsed 
#  3.196   0.000   3.198 
system.time(MatVecMul_cpp(y, 0.9))
#   user  system elapsed 
#  0.840   0.000   0.841 
Java function to build the following square matrix

Java function to build the following square matrix


By : nati55575
Date : March 29 2020, 07:55 AM
Hope that helps I need a function which builds the following matrix, taking (int n) as function argument:
code :
1 

1 3 
4 2 

1 4 8 
6 2 5 
9 7 3 

 1  5 11 15 
 8  2  6 12 
13  9  3  7 
16 14 10  4 

 1  6 14 20 24 
10  2  7 15 21 
17 11  3  8 16 
22 18 12  4  9 
25 23 19 13  5 

 1  7 17 25 31 35 
12  2  8 18 26 32 
21 13  3  9 19 27 
28 22 14  4 10 20 
33 29 23 15  5 11 
36 34 30 24 16  6 

  1  11  29  45  59  71  81  89  95  99 
 20   2  12  30  46  60  72  82  90  96 
 37  21   3  13  31  47  61  73  83  91 
 52  38  22   4  14  32  48  62  74  84 
 65  53  39  23   5  15  33  49  63  75 
 76  66  54  40  24   6  16  34  50  64 
 85  77  67  55  41  25   7  17  35  51 
 92  86  78  68  56  42  26   8  18  36 
 97  93  87  79  69  57  43  27   9  19 
100  98  94  88  80  70  58  44  28  10 
Build a new matrix made of some source matrix rows given a row index vector

Build a new matrix made of some source matrix rows given a row index vector


By : user2991736
Date : March 29 2020, 07:55 AM
Hope that helps With the development branch and (at least) C++11 enabled, you can write:
code :
Eigen::MatrixXi N = m(r1,Eigen::all);
N = m(r1, :);
std::vector<int> c2{{3,0}};
std::cout << "m({2,1},c2) = \n" << m({2,1}, c2) << '\n';
m({2,1}, c2) = Eigen::Matrix2i{{1,2},{3,4}};
std::cout << m << '\n';
Related Posts Related Posts :
  • Using German characters (ü, ö, ä, etc.) in text analysis (R)
  • R JAGS: Dimension mismatch
  • R - How to create a function that accepts a code block as parameter?
  • How do I manually set geom_bar fill color in ggplot
  • How can I get my points to connect in a plot and show a trend with NA values in data?
  • Read SPecific lines of a CSV file in R-language
  • ggplot stacked bar plot from 2 separate data frames
  • auto.arima not parallelizing
  • Histogram of binned data frame in R
  • R rewriting stringmanipulations implemented in loop to the R-way
  • get first entries in rows of list?
  • Conditionally removing rows from a matrix in R
  • Using a loop to find P(-1.5<Y<1.5) for a range of sample sizes
  • R-Count and list the maximum count row by row
  • Include Iverson Bracket in R documentation
  • update a data frame and environment in R
  • How to write dynamic cumulative multiple in R
  • format time using as.POSIX in R
  • Change the class of multiple columns
  • Remove period and spaces within column headings nested in a list of data frames
  • R: error message --- package error: "functionName" not resolved from current namespace
  • labels with geom_text ggplot2
  • Passing mongodb ISODate in R
  • Importing "csv" file with multiple-character separator to R?
  • Change row names of a table obtained from a lm regression using xtable function
  • R language iterate over R object
  • How do you delete the header in a dataframe?
  • 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)
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org