Sum of Multiplication of column values in cell array

4 ビュー (過去 30 日間)
Tha saliem
Tha saliem 2018 年 1 月 4 日
コメント済み: Jan 2018 年 1 月 4 日
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.
  1 件のコメント
Tha saliem
Tha saliem 2018 年 1 月 4 日
(*3*) means bold text (i think its code box so it didn't worked )



Jan 2018 年 1 月 4 日
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}{:});
The actual calculation is a simple matrix multiplication.
  1 件のコメント
Tha saliem
Tha saliem 2018 年 1 月 4 日
Ok I got it. Thank You for helping.


その他の回答 (2 件)

Birdman 2018 年 1 月 4 日
Additional approach to Jan's answer(I tried to eliminate the loop)
Then the rest is just a matrix calculation, as Jan said.
For instance, what you asked in the question is calculated as:
Hope this helps.
  2 件のコメント
Jan 2018 年 1 月 4 日
@Birdman: Exactly. +1. If the intermediate arrays are not huge, this is the most efficient approach.


Guillaume 2018 年 1 月 4 日
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;
x{2,1}= [1,1,5,3.6,4,2.3,3,2,4.12;
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);
  1 件のコメント
Tha saliem
Tha saliem 2018 年 1 月 4 日
Thank You for your time @Guillaume.



Find more on Loops and Conditional Statements 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!

Translated by