0
votes

Let's suppose I have a vector x and 2 constants initialized as follows:

x = [ones(1,21) zeros(1,79)]; %step of 100 components
p = 2; q = 0;

Now, I want to build this matrix:

enter image description here

But in this case for example x(q-1) = x(-1) doesn't exist, so I want it to be 0, and I was wondering if there is a way to do it with the minimum lines of code. Note that the matrix can be written with the function toeplitz(), but I don't know how to replace nonexistent position of my vector x with zeros.

I hope someone can help me. Thank you for your answers.

1
Just to be clear: Is x(q) = x(0) considered the first element of the vector x (Matlab's indexing starts at 1)? Also, the result should be a 100 x 100 matrix(?), and all negative indices should be neglected and the value considered as zero?HansHirse

1 Answers

2
votes

You need to be careful about zero-based or one-based indexing.

In your question, you state that negative indices are invalid - in MATLAB the index 0 is also invalid. The below code assumes your x(q) is zero-based as described, but I do a +1 conversion. Be aware of this if q+p-1 is near numel(x).

x = [ones(1,21) zeros(1,79)]; %step of 100 components
p = 2; q = 0;

% Set up indexing matrix using implicit expansion (R2016b or newer)
m = ( q:-1:q-p+1 ) + ( 0:1:q+p-1 ).';
% Convert from 0-based to 1-based for MATLAB
m = m + 1;
% Set up output matrix, defaulting to zero
M = zeros( size( m ) );
% Put elements where 'm' is valid from 'x' into output 'M'
M( m > 0 ) = x( m( m > 0 ) );

The output is a (q+p) * p matrix.