学习札记之MATLAB:矩阵运算与for循环

MATLAB矩阵运算与for循环

单层的for循环貌似与矩阵运算的区别不大
两层以上的for循环则明显慢于矩阵运算

遇到的问题

用MATLAB做蒙特卡洛仿真时,需要随机生成一个很大矩阵的随机数

for j = 1:length(Pj1)
    j
    Pj = Pj1(j);
for k = 1:length(N1)
    k
    N = N1(k);
    tm(k) = erfenfa(@tm_mtcl,0,10,1e-3);
    tm1 = tm(k);
    if tm1<=9.9
        for i = 1:M
            Jr=RR*sqrt(rand(1,N));Jseta=2*pi*rand(1,N);%协作结点
            Jx=x0+Jr.*cos(Jseta);Jy=y0+Jr.*sin(Jseta);
            J = Jx + 1i * Jy;
            rtr = abs(R0)';rte = abs(E)';rje = abs(J-E)';rjr = abs(J-R0)';
            hjr = exprnd(1,N,1).*(rjr.^(-alpha));
            hje = exprnd(1,N,1).*(rje.^(-alpha));
            hte = exprnd(1,1,1).*(rte.^(-alpha));
            htr = exprnd(1,1,1).*(rtr.^(-alpha));
            A = gt(tm1,hjr);       %筛选 tm改
            hje1 = hje.*A;rje1 = rje.*A;hjr1 = hjr.*A;
            ytr(i) = Pt*htr/(Pj*sum(hjr1)+ctr);
        end
        RcR = @(RR) -RR*(1-out_mt(ytr,RR));
        [x,y] = fminbnd(RcR,0,5);
        Rcm1(k,j) = -y;
        Rm1(k,j) = x;
    else
        Rcm1(k,j) = 0;
        Rm1(k,j) = 0;
    end
end
end

采用矩阵运算之后

Jr=RR*sqrt(rand(M,N));Jseta=2*pi*rand(M,N);%协作结点
Jx=x0+Jr.*cos(Jseta);Jy=y0+Jr.*sin(Jseta);
J = Jx + 1i * Jy;
rje = abs(J-E)';rjr = abs(J-R0)';
hjr = exprnd(1,N,M).*(rjr.^(-alpha));
hje = exprnd(1,N,M).*(rje.^(-alpha));
hte = exprnd(1,1,M).*(rte^(-alpha));
htr = exprnd(1,1,M);
A = gt(tm,hjr);
hje1 = hje.*A;hjr1 = hjr.*A;
FA = Pj*sum(hje1,1)+cte;
DM = Pt*hte+FA;
ytr = Pt*htr./(Pj*sum(hjr1,1)+ctr);
er1 = erP2(FA',DM',mu);
mer = min(er1);
f = mer-e;
Rc = R.*(1-out_mt(ytr,R));
Rcm = max(Rc);

运算速度能比原来提升10倍以上

bsxfun函数的使用

bsxfun(@fun,A,B)是功能很强大的一个函数,能够自定义三维矩阵与二维矩阵或一维矩阵的运算,配合permute函数(交换矩阵的维度)有很好的效果。

function f = Pfa_mt1(FA,mu)
M = size(FA,1);
for i = 1:length(mu)
A = gt(FA,mu(i));
P(i,:) = sum(A,1)/M;
end
f = P;
end

修改后

function f = Pfa_mt2(FA,mu) 
a = size(FA,1);
mu = permute(mu,[3,1,2]);
c = bsxfun(@gt,FA,mu);
P = sum(c,1)/a;
f = permute(P,[3,2,1]);
end

以上两种方式能实现同样的效果。

你可能感兴趣的:(matlab)