How can I replace two for loops with matrix operations to calculate quardatic form?

6 views (last 30 days)
Hello! I'm trying to optimise my code by replacing two for loops with matrix operations. I want to calculate , here is one element of a covariancia matrix, M is a matrix too. The question basically is, how couldI calculate . I tried to just solve , which would look like this with foor loops, with a simple example for vector x:
dim1 = 3;
dim2 = 2;
x = {[1;10] [2;20] [5;50]};
t = cell2mat(x);
c = zeros(dim1);
for i = 1:dim1
for j = 1:dim1
c(i,j) = (t(:, i) - t(:, j))' * (t(:, i) - t(:, j));
I tried the following:
at = repmat(t', [1 dim1]);
bt = repmat(reshape(cell2mat(x'), [1 dim1*dim2]), [dim1 1]);
a = repmat(reshape(cell2mat(x'), [dim1*dim2 1]), [1 dim1]);
b = repmat(t, [dim1 1]);
C = (at-bt) * (a-b);
Here (at-bt) is how I would replace (t(:, i) - t(:, j)) if only that was inside the for loops, and the same goes for (a-b) and (t(:, i) - t(:, j). It doesn't work, and might see why, but I think there shuold bea way to replace this two for loops wint matrix operators using repmat(), reshape(), transpose operator and maybe other matrix operations. So could someone tell me how to replace the two for loops with matrix operators in the origal case or in one of the more simple forms, or could someone give mi a tip what to try?

Accepted Answer

Tommy on 3 Apr 2020
Considering that c(i,j) is the dot product of the difference between the ith and jth columns of t with itself, this should work:
dim1 = 3;
dim2 = 2;
x = {[1;10] [2;20] [5;50]};
t = cell2mat(x);
at = repmat(t, [1 dim1]);
bt = repelem(t, 1, dim1);
C = reshape(dot(at-bt, at-bt), [dim1 dim1]);

More Answers (0)


Find more on General Applications 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!