Home > Net >  Custom function for multiplying all odd values in matrix
Custom function for multiplying all odd values in matrix

Time:11-04

I am trying to code a function in R which takes one argument (matrix) and multiply all odd values in it by 0.618.

for (var in A) {
  if((var %% 2) != 0) {
    updatedVar = var * 0.618
    return(updatedVar)
  }
}

This is what I got so far, but it is my first time working with R matrixes and not sure how to replace values in for loop, or if it's better to do it after multiplying numbers.

CodePudding user response:

You can try the code below

mat <- matrix(1:12, 3, 4)
mat2 <- mat * 0.618^(mat %% 2)

where

  • %% checks the modulo over 2
> mat %% 2
     [,1] [,2] [,3] [,4]
[1,]    1    0    1    0
[2,]    0    1    0    1
[3,]    1    0    1    0
  • 0.618^(...) gives the coefficient
> 0.618^(mat %% 2)
      [,1]  [,2]  [,3]  [,4]
[1,] 0.618 1.000 0.618 1.000
[2,] 1.000 0.618 1.000 0.618
[3,] 0.618 1.000 0.618 1.000

CodePudding user response:

Try this:

mat <- matrix(sample(80), ncol = 10)

ifelse(mat %% 2 != 0, mat * 0.618, mat)

ifelse takes three arguments:

  1. the condition (in your case that the number is divisible by 2)

  2. the value to assign if the condition occurs

  3. the value to be assigned if the condition does not occur

CodePudding user response:

function oddMult takes matrix A and multiplication value v and multiplies add values within matrix A with v:

oddMult <- function(A, v){
  
  indices <- which(A %% 2 == 1)
  A[indices] <- A[indices] * v
  
  A
}

Example:

set.seed(21)
A <- matrix(sample(20, 50, TRUE), 10, 5)
oddMult(A, 0.618)

        [,1]   [,2]   [,3]   [,4]   [,5]
 [1,] 20.000  4.326  6.798  3.090 18.000
 [2,] 10.506 16.000  3.090  2.000 11.742
 [3,]  3.090  4.000 20.000 18.000  3.090
 [4,] 14.000  9.270  5.562 14.000  8.000
 [5,]  4.326 18.000  8.000  9.270  9.270
 [6,]  6.798 18.000 16.000 16.000  9.270
 [7,] 11.742  1.854  5.562 16.000 16.000
 [8,]  4.000  8.034  0.618  1.854  6.000
 [9,]  5.562  6.798  1.854  5.562 16.000
[10,] 10.000  6.798  1.854 12.000  6.000

CodePudding user response:

mat <- matrix(1:12, 3, 4)

mat[mat %% 2 != 0L] <- 0.618 * mat[mat %% 2 != 0L]
mat
#       [,1] [,2]  [,3]   [,4]
# [1,] 0.618 4.00 4.326 10.000
# [2,] 2.000 3.09 8.000  6.798
# [3,] 1.854 6.00 5.562 12.000

Using magrittr to avoid repitition:

library(magrittr)
mat[mat %% 2 != 0L] %<>% {0.618 * .}
  • Related