Search code examples
arraysmatlabcell

How to perform right-array division on two cell array


I have two cell array like: A={<16x1 double>, <37x1 double>, <43x1 double>} and B={<16x1 double>, <37x1 double>, <43x1 double>}. Now, I want to divide each element of cell array A by the corresponding element of cell array B or vice versa! If element of cell array B is bigger than element of cell array A, then the devision should be B./A and then calculate the square root of these values. For Two matrix I know that I can simply write the below code:

if(a > b )
 ratio= sqrt(a ./ b);
else
 ratio= sqrt(b ./ a);   
end

but I don't know how can I extend this algorithm for cell array? I know that I can define two for loops for accessing to every vector of cell array and then apply my above code but this algorithm is too slow and it is not really helpful for large cell array since I have written a code like I mentioned and I saw it is really sucks!! THX for your help


Solution

  • Use cellfun combined with max and min to achieve what you want:

    C = cellfun(@(x,y)sqrt(max(x,y)./min(x,y)), A, B, 'uniformOutput',false)
    

    cellfun applies a function to every element of the cells (the three arrays of length 16, 37, and 43, respectively). 'UniformOutput', false indicates that the output should be returned in a cell array with the same number of elements as the inputs.

    @(x,y) indicates an anonymous function that takes two input arguments (the corresponding arrays from A and B).

    max(x,y) takes the maximum of the corresponding elements of arrays x and y, thus guaranteeing that you always have the maximum in the numerator of the division.