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?
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Quadratic Programming and Cone Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!