Search code examples
matlabmatrixcellelementoperations

Avoiding for-loops in matrix operations with cell elements


The dimensions of this problem are: model.nlf = 4. Each {r} of Kuu or KuuGamma are 500x500 matrices of data.

How to suppress the for-loop? my intuition goes toward using cellfun with a function for logdet.

logDetKuu = 0;
for r=1:model.nlf,
    if isfield(model, 'gamma') && ~isempty(model.gamma)
        [model.Kuuinv{r}, model.sqrtKuu{r}] = pdinv(model.KuuGamma{r});
        model.logDetKuu{r} = logdet(model.KuuGamma{r}, model.sqrtKuu{r});
    else
        [model.Kuuinv{r}, model.sqrtKuu{r}] = pdinv(model.Kuu{r});
        model.logDetKuu{r} = logdet(model.Kuu{r}, model.sqrtKuu{r});
    end
    logDetKuu = logDetKuu + model.logDetKuu{r};
end

Grateful for pointers. Thanks

Follow up question: Can the following type of for-loops on cell elements be vectorized? nlf = 4; nout = 16; each KuuinvKuy{1,1} are 150x650

for k =1: model.nout,
    for r =1: model.nlf,
        model.KuuinvKuy{r,k} = model.Kuuinv{r}*model.Kyu{k,r}';
    end
end

Solution

  • If all your matrices are so large, and you execute your for-loop only 4 times, then there is no reason to remove the for-loops, since it will not lead to any speedup. My only observation is that the condition of the if seems to be independent of the loop, so it is cleaner to move that if before the loop. Something like this:

    if isfield(model, 'gamma') && ~isempty(model.gamma)
        myKuu = model.KuuGamma;
    else
        myKuu = model.Kuu;
    end
    
    logDetKuu = 0;    
    for r=1:model.nlf,
        [model.Kuuinv{r}, model.sqrtKuu{r}] = pdinv(myKuu{r});
        model.logDetKuu{r} = logdet(myKuu{r}, model.sqrtKuu{r});
        logDetKuu = logDetKuu + model.logDetKuu{r};
    end