Avoid for loops, use cell operation to do: r2' * r1 * l1' * l2

Hi all,
Say I have 2 simple 1-by-2 cells, I'd like to perform operation like this: r2' * r1 * l1' * l2 to obtain a 2-by-2 matrix, sample code as follows:
clear; clc;
% the cells.
bl = {1 2};
br = {3 4};
% element 1.
l1 = bl{1, 1};
l2 = bl{1, 1};
r1 = br{1, 1};
r2 = br{1, 1};
otpt11 = r2' * r1 * l1' * l2;
% element 2.
l1 = bl{1, 2};
l2 = bl{1, 1};
r1 = br{1, 2};
r2 = br{1, 1};
otpt12 = r2' * r1 * l1' * l2;
% element 3.
l1 = bl{1, 1};
l2 = bl{1, 2};
r1 = br{1, 1};
r2 = br{1, 2};
otpt21 = r2' * r1 * l1' * l2;
% element 4.
l1 = bl{1, 2};
l2 = bl{1, 2};
r1 = br{1, 2};
r2 = br{1, 2};
otpt22 = r2' * r1 * l1' * l2;
% put all elements together.
otpt = [otpt11 otpt12; otpt21 otpt22];
I can probably use for loops to do it, but I'd like to use a compact operation such as cellfun to do it, which I believe is faster and more nature for cells.
Many thanks!

6 Comments

cellfun uses loop inside. I think better is to use loops.
@Xh Du: why are you using cell arrays to hold numeric data? Why not use simple numeric arrays? If you put your data into numeric arrays then this would be a trivial operation.
Yes.....that's correct..
Well, because in my real problem these numeric are vectors, so I put these vectors into cells to make it clearer rather than putting all vectors into arrays.
I know that this will work:
bl = [1 2];
br = [3 4];
b = bl .* br;
otpt = b' * b;
But for my case I have to keep bl and br separated, i.e. no .* operation, but to use "r2' * r1 * l1' * l2". Actually originally I have b = [3 8], bl and br are decomposed from b.
Use loops. They are fast and clean, if you pre-allocate the output.

Sign in to comment.

Answers (0)

Categories

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

Asked:

on 9 May 2017

Commented:

on 9 May 2017

Community Treasure Hunt

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

Start Hunting!