How to multiply a matrix to another cell matrix

30 Ansichten (letzte 30 Tage)
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor am 14 Mai 2021
Bearbeitet: Stephen23 am 14 Mai 2021
Hello
I have a 3*3 matrix such as
[1 0 0;
8 23 1;
5 7 10]
On the other hand, I have matrix 2000*1 containing 2000 cell arrays which are 3*4 matrices such as
[ [3*4];
[3*4];
[3*4];
.
.
]
I want to multiplythis 3*3 matrix to each of 3*4 matrices in the big matrix and obtain a final 2000*1 matrix. I have seen the code @(x)x.*matrix in MATLAB forum.
However, it gives out a function handle..I need to use the numeric output. What should i do?
  1 Kommentar
David Hill
David Hill am 14 Mai 2021
You need to explain more. How are you getting a 2000x1 matrix? What do you mean when you say multiply? 3x3 * 3x4 = 3x4 matrix, you cannot perform element-wise multiplication on different sized matrices.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephan
Stephan am 14 Mai 2021
Bearbeitet: Stephan am 14 Mai 2021
Use cellfun:
A = magic(3)
A = 3×3
8 1 6 3 5 7 4 9 2
C = {rand(3,4); rand(3,4); rand(3,4); rand(3,4); rand(3,4)}
C = 5×1 cell array
{3×4 double} {3×4 double} {3×4 double} {3×4 double} {3×4 double}
result = cellfun(@(x)mtimes(A,x),C,'UniformOutput',false)
result = 5×1 cell array
{3×4 double} {3×4 double} {3×4 double} {3×4 double} {3×4 double}
C{1}
ans = 3×4
0.7660 0.7423 0.4707 0.8602 0.4490 0.2799 0.8553 0.2608 0.4265 0.9783 0.5613 0.8271
result{1}
ans = 3×4
9.1360 12.0880 7.9885 12.1046 7.5281 10.4742 9.6180 9.6741 7.9578 7.4446 10.7034 7.4423
  3 Kommentare
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor am 14 Mai 2021
BTW, Is there any faster approach?
Stephen23
Stephen23 am 14 Mai 2021
"Is there any faster approach?"
Use a loop (with preallocation).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 14 Mai 2021
Bearbeitet: Jan am 14 Mai 2021
Create a simple loop:
A = rand(3, 3);
for iC = 1:numel(C) % Where C is your cell
C{iC} = A * C{iC};
end
The approach with cellfun looks smart, but it is slower:
C = cellfun(@(c) A*c, C, 'UniformOutput', false);
By the way, .* is the elementwise operation. You need *, because the matrix and the cell elements do not have the same number of elements.
  2 Kommentare
Stephan
Stephan am 14 Mai 2021
@Jan will this be faster than cellfun for a big number of operations?
Stephen23
Stephen23 am 14 Mai 2021
Bearbeitet: Stephen23 am 14 Mai 2021
"will this be faster than cellfun for a big number of operations? "
Yes.
Try it.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by