Home > OS >  Converting MATlab Loop to R - Cell Structures
Converting MATlab Loop to R - Cell Structures

Time:09-23

I am having trouble to convert a Matlab loop into R.

For every {t,tau}, calculate the o indexed with a value that refers to the value of [t,tau] from within the loop. In the matlab code it is done via a cell structure that applies from outside the loop.

o{1,1} = [1 0]';
o{1,2} = [0 0]';
o{2,1} = [1 0]';
o{2,2} = [0 1]';

Within the loop something like this is calculated:

nat_log(A'*o{t,tau})

How can I manage the loop to use the values of t and tau that I set within the loop in order to adress certain "o" within a list?

First my attempt:

Timesteps = 2 # total timesteps/iterations
Tau = 2       # amounts of observations o within 1 timestep; at t=1 and tau-1 = o = [0 0], above denoted {1,2}

for(t in 1:length(Timesteps)){
            qs[,t] = matrix(c(.5,.5))         # This is the posterior distribution to be updated, 
    for (t in 1:length(Timesteps)){                   # but that's not that important
        for (tau in 1:length(Timesteps)){
               ****some more math****
            y = x * o[[t,tau]]                # THIS is the important part!                
       etc. .... ..... .... ....

I tried something like

o<- vector("list", length = 2 * 2)
dim(o) <- matrix(c(2, 2))

o[[1,1]] <- matrix(c(1, 0), nrow = 2, ncol =1, byrow = TRUE)
o[[1,2]] <- matrix(c(0, 0), nrow = 2, ncol =1, byrow = TRUE)
o[[2,1]] <- matrix(c(1, 0), nrow = 2, ncol =1, byrow = TRUE)
o[[2,2]] <- matrix(c(0, 1), nrow = 2, ncol =1, byrow = TRUE)

The orginial matlab code that I am trying to reproduce can be found here: https://github.com/rssmith33/Active-Inference-Tutorial-Scripts/blob/main/Pencil_and_paper_exercise_solutions.m

Line: 46-103 (it is essentially Bayes inference with Markov property...)

If someone has an idea, I would be very thankful. I am just a med student interested in math and would love to see this available for R as well.

CodePudding user response:

I worked it out!

The loop can be found here, if anybody else has a similar questions in the future. Here is the full R code: https://github.com/StSchwerdtfeger/Tutorials/blob/main/PencilandPaperExampleinR.R

  • Related