title: Calculating BER for BPSK in Matlab
body: <p>I wrote this code for comparing manually calculated BER and theoretical BER graphically.</p>
  
  <p>The manually calculated BER (err) is always 1x1 value and I want it as a range of values corresponding to SNR values.</p>
  
  <p>I also replaced this line:</p>
  
  <pre><code>err=error+1;
  </code></pre>
  
  <p>with this line:</p>
  
  <pre><code>err(k)=error+1; 
  </code></pre>
  
  <p>and still not working. </p>
  
  <p>Can anybody solve this problem?</p>
  
  <p>Here is the code:</p>
  
  <pre><code>N=100;                               % number of bits
  
  SNR=0:1:10;                          % Different values for SNR
  
  err=zeros(1:length(SNR));            % Initilizing calculated error for 
                                       % different SNR values
  
  for k=1:1:length(SNR)
  
      N0(k)=10^(-SNR(k)/10);            % Calculating the noise level
  
      s=randn(1,N)&gt;.5;                 % generating random number of logic bits
                                       % with equal probability 0.5    
      s=2*s-1;                         % Generating BPSK sequence between logic 1 , -1
  
                                       % Generating real random noise with SD of 0.1
      n = sqrt(N0(k)/2)*(randn(1,N) + j*randn(1,N));   
  
      r=s+n;                           % Noisy signal 
  
      rd=zeros(1,N);                   % Initializing Detected signal
  
          for i=1:1:N
  
              if(r(i)&gt;0)              % Comparing detected signal against a threshold
                  rd(i)=1;
              else
                  rd(i)=0;         
              end
          end
  
      error=0;
  
          for j=1:1:N                 % calculating BER
  
              if(abs(rd(j)-s(j))==1)
                  error=error+1;        
              end
          end
  
  
          err=error+1;                   % calculated error for this value of SNR
  
  end
  
  th_err=.5*erfc(sqrt(10.^(SNR/10)));   % Theoretical BER
  
  semilogy(SNR,th_err,'*r');grid on;title('Bit error rate for BPSK');xlabel('Eb/N0');ylabel('Theoritical BER');
  </code></pre>