Ben B.
Ben B.

Reputation: 97

How to apply Equation to Cell Array that is a <12x1 cell>

I have two cell arrays that are <12x1 cell> and they are labeled A and B. Each one contains 12 matrices that are <45x13 double> each. Inside each cell there are the matrices: A1,A2,...A12 and B1,B2,...B12.

Is there a way to have an equation output take each pair into account without having to write out twelve instances of the equation?

So create a new matrix that has the results from running this calculation on pairs A1 and B1, A2 and B2,... A12,B12

For example:

averageB = sum(B)/length(B);
averageA = sum(A)/length(A);
tapWithSign = (averageB - averageA) ./ (averageB + averageA / 2) * 100;
tapAB = abs(tapWithSign); 

Upvotes: 1

Views: 802

Answers (1)

Eitan T
Eitan T

Reputation: 32930

Method #1

The straighforward approach is to do it with a for loop:

C = [];
for i = 1:numel(A);
    C(i).averageB = sum(B{i}) / length(B{i});
    C(i).averageA = sum(A{i}) / length(A{i});
    C(i).tapWithSign = (C(i).averageB - C(i).averageA) ./ ...
       (C(i).averageB + C(i).averageA / 2) * 100;
    C(i).tapAB = abs(tapWithSign{i});
end

I wasn't sure how you want the results to be stored, so I have stored them in C, which is an array of structs, with the calculation results as fields.


Method #2

Alternatively, you can use cellfun like so:

averageA = cellfun(@(x)(sum(x)/length(x)), A, 'Un', 0);
averageB = cellfun(@(x)(sum(x)/length(x)), B, 'Un', 0);
tapWithSign = cellfun(@(x, y)deal((y - x) ./ (y + x / 2) * 100), ...
    averageA, averageB, 'Un', 0);
tapAB = cellfun(@abs, tapWithSign, 'Un', 0);

Note that this yields the calculation results as cell arrays. If you want to store them in a struct, like in the first example:

C = struct('averageA', averageA, 'averageB', averageB, ...
    'tapWithSign', tapWithSign, 'tapAB', tapAB);

Upvotes: 2

Related Questions