matlabfor-loopcell-array

For cycle: calculation inside cells


I have this line of code:

clear MUCV
 for c = 1:size(CVV,2)
     r = 1:size(CVV,1);
     MUCV(r,c) = (round(100*median(abs(CVV{c}(CCC{c}>0.8))))/100);
 end

Where CVV and CCC are two equal matrices containing cells, and I have to apply that calculation to each cell.

The problem is that, in this for cycle, the calculation is done only for the first row and then copies in MUCV the same row many times as specified in r.

If I add {r and c} in the following it gives me an error.

MUCV(r,c) = (round(100*median(abs(CVV{r,c}(CCC{r,c}>0.8))))/100);

Solution

  • If I understood correctly, you want to extract all the elements that match the constraint CCC{c}>0.8 from CVV{c}. I reckon MATLAB will not allow you to do that in a one-step fashion and you must do it in separate steps.

    The problem is with r. You have to create a nested for loop in order to scan every element according to indices c and r, like this:

    for c = 1:size(CVV,2)
        for r = 1:size(CVV,1);
            % do something
        end
    end
    

    But you must edit the inner line since, again, I reckon it won't work. Maybe try something like:

    for c = 1:size(CVV,2)
        for r = 1:size(CVV,1);
            SelectedCVV=CVV{r,c};
            MUCV(r,c) = (round(100*median(abs(SelectedCVV(CCC{r,c}>0.8))))/100);
        end
    end
    

    You can as well reach the same results by using cellfun() instead of the nested loops. This function allows you to perform the same function to each cell in a cell array. In your case, you should use something like

    MUCV=cellfun(@(x,y) round(100*median(abs(x(y>0.8))))/100,CVV,CCC)
    

    where x and y are the single cells in (respectively) CVV and CCC.