al_hamnan
al_hamnan

Reputation: 13

Constructing matrices in MATLAB

I am trying to construct few matrices in MATLAB. Programming is not my forte and I cannot go into this. I know I should nest with for loops, but can't figure out how.I have an array of data y with T values. I need to set a lag m and then find Tm=T-2m+1. The matrices Ymin and Yplus have order m x Tm, but don't know how to set them. In parentheses the position of the data in the array. Sorry for the format. The matrices are:

      y(m)      y(m+1)   ...   y(T-m)
      y(m-1)    y(m)     ...   y(T-m-1) 
        .
        .
        .
       y(1)      y(2)    ...   y(Tm)

and

      y(m+1)    y(m+2)     ...   y(T-m+1)
      y(m+2)    y(m+3)     ...   y(T-m-2) 
        .
        .
        .
       y(2m)      y(2m+1)  ...   y(T)

Upvotes: 1

Views: 84

Answers (3)

markjunior
markjunior

Reputation: 26

Hope the following matlab code can help you!

%by Mark 4/28/2015

clear all;
%%%%%%%%%%%%%%%%% take an example

m=4; 
T=10;
y=zeros(1,T);

for i=1:(T)
    y(i)=i;
end

%%%%%%%%%%%%%%%%%%%%%% calculate Ymin

count_i=0;

for i=m:1:(T-m)

    count_i=count_i+1;

    count_j=0;

    for j=i:(-1):(i-m+1)
        count_j=count_j+1;
        Ymin(count_j,count_i)=y(j);
    end
end

Ymin

%%%%%%%%%%%%%%%%%%%%%% calculate Ymax

count_i=0;

for i=(m+1):1:(T-m+1)
    count_i=count_i+1;
    count_j=0;
    for j=i:1:(i+m-1)
        count_j=count_j+1;
        Ymax(count_j,count_i)=y(j);
    end
end

Ymax

Upvotes: 1

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can use hankel or toeplitz functions.

For first matrix use

flipud(hankel(y(1:m), y(m:Tm))

or

toeplitz(y(m:-1:1), y(m:Tm))

And for the second matrix use

hankel(y(m+1:2*m), y(2*m:T))

Upvotes: 0

Divakar
Divakar

Reputation: 221514

One approach with bsxfun to get those two matrices -

T = numel(y) %// number of elements in y

idx1 = bsxfun(@plus,[m:-1:1]',0:Tm-1)
out1 = y(idx1)

idx2 = bsxfun(@plus,[m+1:2*m]',0:Tm-1)
out2 = y(idx2)

Upvotes: 3

Related Questions