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

3 次查看(过去 30 天)
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));
end
end
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?

采纳的回答

Tommy
Tommy 2020-4-3
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]);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Quadratic Programming and Cone Programming 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by