Search code examples
matlabmismatch

matlab Subscripted assignment dimension mismatch.


I had built this script but i can't find the problem Matrix in it. this is my script for reply a call standard option:

N=50;
T=90/252;
dt=T/N;
K=102;
S0=100;
B0=1;
r=0.02;

sigma=0.25;



for i=1:N
    ttomat(i)=(N-i+1)*dt;   %+1 serve per aggiustare il tempo
    d1(i)=(log(S(i,:)./K)+(r+0.5*sigma^2)*ttomat(i))./(sigma*sqrt(ttomat(i)));
    d2(i)=d1(i)-sigma*sqrt(ttomat(i));
    Call(i,:)=S(i,:).*normcdf(d1(i))-K*exp(-r*ttomat(i)*normcdf(d2(i)));
    alpha(i,:)=normcdf(d1(i));    %delta della Call 
    beta(i,:)=(Call(i,:)-alpha(i,:).*S(i,:))./(B0*exp(r*(i-1)*dt));

end

Solution

  • You have to initialize/pre-allocate the result, which gets calculated in loops. In your code, you have not pre-allocated the results. Pre-allocation helps you in achieving your result fast. It is always a best practice to pre-allocate the required variables. Check the below code, is it working for you?

    N=50;
    T=90/252;
    dt=T/N;
    K=102;
    S0=100;
    B0=1;
    r=0.02;
    
    sigma=0.25;
    
    S = rand(N,1) ;
    
    ttomat = zeros(1,N) ;
    d1 = zeros(1,N) ;
    d2 = zeros(1,N) ;
    Call = zeros(1,N) ;
    alpha = zeros(1,N) ;
    beta = zeros(1,N) ;
    for i=1:N
        ttomat(i)=(N-i+1)*dt;   %+1 serve per aggiustare il tempo
        d1(i)=(log(S(i,:)./K)+(r+0.5*sigma^2)*ttomat(i))./(sigma*sqrt(ttomat(i)));
        d2(i)=d1(i)-sigma*sqrt(ttomat(i));
        Call(i,:)=S(i,:).*normcdf(d1(i))-K*exp(-r*ttomat(i)*normcdf(d2(i)));
        alpha(i,:)=normcdf(d1(i));    %delta della Call 
        beta(i,:)=(Call(i,:)-alpha(i,:).*S(i,:))./(B0*exp(r*(i-1)*dt));
    
    end