How can I replace two for loops with matrix operations to calculate quardatic form?
3 ビュー (過去 30 日間)
古いコメントを表示
Csanad Levente Balogh
2020 年 4 月 3 日
コメント済み: Csanad Levente Balogh
2020 年 4 月 4 日
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!