提高代码的性能以解决方程式

时间:2016-12-08 04:23:50

标签: matlab performance optimization equation-solving approximation

我对MATLAB很新手,我正在努力寻找这个等式的解决方案。

enter image description here

矩阵的维数为{λ} = N×K,{Y} = N×D,{π} = 1×K,{μ} = D×K。

我创建的内容看起来更像是一个怪物,而不是一个有效的MATLAB代码,这是由于严重缺乏MATLAB技能。

实际上,我决定逐步解决这个问题,以便熟悉MATLAB的工作原理。我最终得到了一个超低效的代码,我甚至无法将它组合起来。即使最终结果也是错误的,因为我想创建一个NxK矩阵。任何指导都将非常感谢。

%Dimensions:
nn = 10;
dd = 7;
kk = 5;

%Initial variables:
lambda0 = rand(nn,kk);
sigma = rand(1);
Y = rand(nn,dd);
mu = rand(dd,kk);

%Calculate pies:
First_part = log(pie(:)./(1.-pie(:))); % Kx1 vector

%Calculate Second part:
for n = 1:nn
for d = 1:dd
lambda_mu(d,:) = lambda0(n,:).*mu(d,:); %lambdamu is a DxK matrix
end
lambda_mu2(n,:) = sum(lambda_mu,2); %This is a NXD matrix
end

%Y-lambdamu2:
for n = 1:nn
YY(n,:) = Y(n,:)-lambda_mu2(n,:); % This is a NxD vector
end

%YY*mu:
Second = (YY*mu)./sigma^2; % NxK

%Third:
Third = (mu'*mu)./2*sigma^2; % KxK

%Final:
for n=1:nn
Final_part = transpose(First_part(:))+Second(n,:)-Third;
end

更新1好的,我欠我一杯啤酒。所以,我通过修改我的代码创建{λ} = N×K矩阵取得了一些进展,如下所示: / p>

更新[2]:花费太多时间编程,你错过了细节。我修正了错误,因为我设置了{Y} = D×K,而不是{Y} = D×N。

%Dimensions:
nn = 10;
dd = 7;
kk = 5;

%Initial variables:
lambda0 = rand(nn,kk);
sigma = rand(1);
Y = rand(dd,nn);
mu = rand(dd,kk);
pie = rand(1,kk);
sigma = rand(1);

%Calculate the equation.
for n = 1:nn
for k = 1:kk
    lambda(n,k) = log(pie(k)/(1-pie(k))) + (transpose(Y(:,n)-... 
        (sum(lambda0(n,1:end ~= k).*mu(:,1:end ~= k),2)))*mu(:,k))/...
        sigma^2 - transpose(mu(:,k))*mu(:,k)/2*sigma^2;
end
end

但是,现在问题是它只能达到n = 5,当我尝试循环n = 6例如我得到这样的信息:“索引超出矩阵维度”,所以实际上我只得到5×5矩阵。建议好吗?

P.S:我甚至试图将lambda从lambda(n,k)改为lambda(k,n),但结果却是一样的。

1 个答案:

答案 0 :(得分:0)

为了使尺寸有效,请乘以ones(nn,kk)ones(1,kk)

nn = 10;
dd = 7;
kk = 5;

%Initial variables:
lambda0 = rand(nn,kk);
sigma = rand(1);
Y = rand(nn,dd);
mu = rand(dd,kk);
pie = rand(kk,1);

%Calculate pies:
First_part = ones(nn,kk)*log(pie./(1.-pie))*ones(1,kk); % Kx1 vector

%Calculate Second part:
for n = 1:nn
    for d = 1:dd
        lambda_mu(d,:) = lambda0(n,:).*mu(d,:); %lambdamu is a DxK matrix
    end
    lambda_mu2(n,:) = sum(lambda_mu,2); %This is a NXD matrix
end

%Y-lambdamu2:
for n = 1:nn
    YY(n,:) = Y(n,:)-lambda_mu2(n,:); % This is a NxD vector
end

%YY*mu:
Second_part = (YY*mu)./sigma^2; % NxK

%Third:
Third_part = ones(nn,kk)*(mu'*mu)./2*sigma^2; % KxK


%Final:
for n=1:nn
    Final_part(n,:) = First_part(n,:)+Second_part(n,:)-Third_part(n,:);
end
编辑:我的想法更像是:

%Initial variables:
lambda = rand(nn,kk);
sigma = rand(1);
y = rand(nn,1);
mu = rand(nn,kk);
pie = rand(1,kk);

%Calculate pies:
First_part = ones(nn,1)*log(pie./(1-pie)); % NxK vector

避免循环。

也许使用类似的东西:

ones(kk)-diag([ones(kk,1)])

i上的总和不等于j时,或者更确切地说使用第三维代表j