是否可以在一个循环中完成整个工作?

Is it possible to make the whole work in one loop?

下午好, 我想知道我在 MATLAB 中所做的工作是否可以在循环中完成,而不是重复相同的方程式来改变相同的变量?

r=1:0.1:20;
A=(r+1./r)./4;
%%%%%%%%%%%%%%%%%%%%%%%%%
x1=0;
R1=((r+1./r)-2)./((r+1./r)+x1);
B1=(1-(x1/2)^2)^-0.5;
NUM1= 2 + (0.5.*x1.*(r+1./r));
DUM1=(r- 1./r ).*(1-(x1/2)^2)^0.5;
C1=EA(NUM1./DUM1);
G1=A.*B1.*C1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x2=-0.1;
R2=((r+1./r)-2)./((r+1./r)+x2);
B2=(1-(x2/2)^2)^-0.5;
NUM2= 2 + (0.5.*x2.*(r+1./r));
DUM2=(r- 1./r ).*(1-(x2/2)^2)^0.5;
C2=EA(NUM2./DUM2);
G2=A.*B2.*C2;

figure
plot(r,G1,'b',r,G2,'r',r,G3,'g',r,G4,'k',r,G5,'c',r,G6,'y','Linewidth',3)
xlabel('$r$','Interpreter','latex','FontSize',18)
ylabel('$G=\gamma P_P L$','Interpreter','latex','FontSize',18)
title('Gain vs r for different values of D/sqrt(M)')
legend('0','-0.1','-1','-1.5','0.5','1.5','1')
%% The function  G for different values of x(or equivalent R) are plotted below sigma 0 %is a notation i am using for different R
figure
plot(R1,G1,'b--',R2,G2,'r',R3,G3,'g',R4,G4,'k',R5,G5,'b--',R6,G6,'r','Linewidth',3)
xlabel('$\sigma_0$','Interpreter','latex','FontSize',18)
ylabel('$G=\gamma P_P L$','Interpreter','latex','FontSize',18)
title('Gain vs r for different values of D/sqrt(M)')
legend('0','-0.5','0.1','1')

所以我的问题是,与其重复相同的方程式 R 和 G 只是为了改变一个变量,我们是否可以将相同的工作做 10 次并通过使用循环缩短代码并仍然得到相同的图? 谢谢

你应该在一个函数中扭曲所有东西,比如:

function rxPlot(r,x)
A = (r+1./r)./4;
G = zeros(length(A),length(x));
R = zeros(length(A),length(x));

for k=1:length(x)
    R(:,k) = ((r+1./r)-2)./((r+1./r)+x(k));
    B = (1-(x(k)/2)^2)^-0.5;
    NUM = 2 + (0.5.*x(k).*(r+1./r));
    DUM = (r- 1./r ).*(1-(x(k)/2)^2)^0.5;
    C = EA(NUM./DUM);
    G(:,k) = A.*B.*C;
end   
plot(r,G,'Linewidth',3)
xlabel('$r$','Interpreter','latex','FontSize',18)
ylabel('$G=\gamma P_P L$','Interpreter','latex','FontSize',18)
title('Gain vs r for different values of D/sqrt(M)')
legend('0','-0.1','-1','-1.5','0.5','1.5','1')

figure;
plot(R,G,'Linewidth',3)
xlabel('$\sigma_0$','Interpreter','latex','FontSize',18)
ylabel('$G=\gamma P_P L$','Interpreter','latex','FontSize',18)
title('Gain vs r for different values of D/sqrt(M)')
legend('0','-0.1','-1','-1.5','0.5','1.5','1')
end

然后简单地用你的输入调用它:

r = 1:0.1:20;
x = [0 -0.1 -1 -1.5 0.5 1.5 1];
rxPlot(r,x)

这是按需要工作的吗?