Multiply each individual cell by a single matrix

I need to multiply each cell of a cell array by a single matrix, and store the result in the same size cell array.
I know how to do this with a for loop, but I was wondering if there was a faster/more efficient way?
For example:
Cell = {[1 2; 3 4; 5 6]; [7 8; 9 10; 11 12]};
matrix = [1 2; 3 4];
Then I would want Cell{1} * matrix stored in result{1}, Cell{2} * matrix stored in result{2}, so on and so forth till I get:
result = {[Cell{1} * matrix]; [Cell{2} * matrix]};
result =
{[7 10; 15 22; 23 34]; [31 46; 39 58; 47 70]}
Is it possible to perform this without a for loop?

 Accepted Answer

Result=cellfun(@(x)x*matrix,Cell,'un',0)

2 Comments

i have 2*1 cell array with size 242*234
and matrix of size 242*234
how to apply above code for it.
i am trying with this
Result=cellfun(@(x)x*matrix,Cell,'un',0)
then i get following error
Error in @(x)x*matrix
or if i try with
matrix=matrix.'
then it gives the out put of 242*242.
In my case i need 242*234 matrix.
please help me to solve this.
thanks in advance.
Tim
Tim on 3 May 2022
Edited: Tim on 3 May 2022
@Leela Sai Krishna, matrix multiplication with two matrices of size M x N that results in a matrix of size M x N is not algebraically possible unless M=N because the inner dimensions must agree.
If you want to do elementwise multiplication, so that
A.*B = [a11*b11 a12*b12 ... a1n*b1n;
a21*b21 a22*b22 .... a2n*b2n;
: : .. :
aM1*bM1 a*2M*b2M ... aNM*bNM]
Then you can use the "dot-multiply" operator with the same code snippet that @madhan ravi provided. In other words, include a period before the asterisk like this:
Result=cellfun(@(x)x.*matrix,Cell,'un',0)

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 4 Feb 2019

Edited:

Tim
on 3 May 2022

Community Treasure Hunt

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

Start Hunting!