Sum of Multiplication of column values in cell array

3 views (last 30 days)
hey i have a cell array x
x{1,1}= {[ *3*,1,6.9,3.6,4,2.3,3,5,4.12],[ *3*,1,4,3,4,2,3.4,5,4],[ *3*,1.9,4,9.21,4,2.2,3,5,4.2],[ *2*,1.8,3.8,2,4,2.1,4,5,4.1]}
x{2,1}= {[1,1,5,3.6,4,2.3,3,2,4.12],[3,4,4,3,4,2,8,5,4],[1,5,4,7,4,2.9,3,5,4.2],[3,1.9,4.8,2,4,2.1,5,5,6]}
and similarly other elements x{3,1} x{4,1} etc. And other array y:
y= {[1,2,1.2,0.2];[0.32,0.42,0.4,0.07]}
I want to take each col value one by one and multiply it with the corresponding value in y and then add them all. Like this:
(3*1) + (3*2) + (3*1.2) + (2*0.2) [3,3,3,2 are bold values in x{1,1}]
and similarly take 2nd col of each element of x{1,1} and multiply it with corresponding values of y{1,1} and add them. When it comes to x{2,1}, it will be multiplied with y{2,1}.
Please suggest any efficient way of doing this without using multiple loops. Thank You.

Accepted Answer

Jan
Jan on 4 Jan 2018
It is much easier to work with multi-dimensional arrays instead of nested cells. The cell arrays require loops for numerical operations, such that they are a bad choice, if you want to avoid loops. But you can convert the data:
Result = cell(size(x));
for k = 1:numel(x)
Result{k} = y{k} * cat(1, x{k}{:});
end
The actual calculation is a simple matrix multiplication.

More Answers (2)

Birdman
Birdman on 4 Jan 2018
Additional approach to Jan's answer(I tried to eliminate the loop)
a=cell2mat(x{1,1}.');
b=cell2mat(y);
Then the rest is just a matrix calculation, as Jan said.
For instance, what you asked in the question is calculated as:
b(1,:)*a(:,1)
Hope this helps.
  2 Comments
Jan
Jan on 4 Jan 2018
@Birdman: Exactly. +1. If the intermediate arrays are not huge, this is the most efficient approach.

Sign in to comment.


Guillaume
Guillaume on 4 Jan 2018
What is the reason for the cells of x to be themselves cell arrays? Due to your multiplication requirements each vector in these subcells must be the same length. Therefore they'd be better stored as a 2D matrix instead, i.e.:
x{1, 1} = [3,1,6.9,3.6,4,2.3,3,5,4.12;
3,1,4,3,4,2,3.4,5,4;
3,1.9,4,9.21,4,2.2,3,5,4.2;
2,1.8,3.8,2,4,2.1,4,5,4.1];
x{2,1}= [1,1,5,3.6,4,2.3,3,2,4.12;
3,4,4,3,4,2,8,5,4;
1,5,4,7,4,2.9,3,5,4.2;
3,1.9,4.8,2,4,2.1,5,5,6];
You can transform your current x in the above x with
x = cellfun(@(c) vertcat(c{:}), x, 'UniformOuput', false);
With that storage, then your problem becomes a simple matrix multiplication of y cells with the x cells, which can be achieved with a single cellfun
result = cellfun(@mtimes, y, x, 'UniformOutput', false);

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!