MATLAB: I am new to matlab and getting matlab error .The error is Error using + Matrix dimensions must agree. Error in RL_Multilayered (line 30) n1=(Z0*tan​h(gamma1*d​1))+sqrt(1​/ebA);

clear all close all clc
load Mul.txt
d1=3e-3; %%%%thickness
d2=3e-3;
d3=2e-3;
d4=2e-3;
f=(10^9)*Mul(:,1); %%%%%frequency
eb1a=Mul(:,2);%%%ebslon real part



eb1b=Mul(:,3);%%%ebslon imaginary part



ebA=complex(eb1a,-eb1b); %%%ebs complex



eb2a=Mul(:,4);%%%ebslon real part
eb2b=Mul(:,5);%%%ebslon imaginary part
ebB=complex(eb2a,-eb2b); %%%ebs complex
eb3a=Mul(:,6);%%%ebslon real part
eb3b=Mul(:,7);%%%ebslon imaginary part
ebC=complex(eb3a,-eb3b); %%%ebs complex
eb4a=Mul(:,8);%%%ebslon real part
eb4b=Mul(:,9);%%%ebslon imaginary part
ebD=complex(eb4a,-eb4b); %%%ebs complex
c=3*10^8;%%%speed of light
Z0=377;
j=sqrt(-1);
gamma1=2*pi*f*(1/c)*sqrt(1/ebA);%%%k1 imaginary

m1=sqrt(1/ebA)*tanh(gamma1*d1)+Z0;
n1=(Z0*tanh(gamma1*d1))+sqrt(1/ebA);
Z1=m1/n1;
gamma2=2*pi*f*(1/c)*sqrt(1/ebB);%%%k1 imaginary
m2=sqrt(1/ebB)*tanh(gamma2*d2)+Z1;
n2=(Z0*tanh(gamma2*d2))+sqrt(1/ebB);
Z2=m2/n2;
k3=1i*2*pi*f*(1/c).*sqrt(1.*ebC);%%%k3 imaginary
m2=Z2+Z0*sqrt(1./ebC).*tanh(k3*d3); %%%Layer 2



n2=Z0*sqrt(1./ebC)+Z2.*tanh(k3*d3); %%%Layer 2
Z3=(m2/n2)*Z0*sqrt(1./ebC);
k4=1i*2*pi*f*(1/c).*sqrt(1.*ebD);%%%k4 imaginary
m3=Z3+Z0*sqrt(1./ebD).*tanh(k4*d4); %%%Layer 2
n3=Z0*sqrt(1./ebD)+Z3.*tanh(k4*d4); %%%Layer 2
Z4=(m3/n3)*Z0*sqrt(1./ebD);
RL=20*log10(abs((Z2-Z0)/(Z2+Z0)));
figure(1)
subplot(211)
plot(f,real(Z2),'Linewidth',2),grid
ylabel('Real part z2')
subplot(212)
plot(f,imag(Z2),'Linewidth',2),grid,shg
xlabel('Frequency HZ')
ylabel('Imaginary part z2')
figure(2)
plot(f,RL,'Linewidth',2),grid
ylabel('RL')
xlabel('Frequency HZ')

Best Answer

ezhar - try using the MATLAB debugger to troubleshoot what the problem might be. If you put a breakpoint at the line
n1=(Z0*tanh(gamma1*d1))+sqrt(1/ebA);
and then run your script, you will notice that gamma1 is an mxm matrix and sqrt(1/eba) is a 1xm matrix (where m is the number of rows in Mul). Since the code is trying to add two matrices of different dimensions, then the error message makes sense. What are you expecting to happen at this line of code?
Note that your frequency f is a column vector too which then makes gamma1 an mxm. Is this correct?
Related Question