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)); endend
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?
Best Answer