how to create a matrix from a vector in this style

1 view (last 30 days)
sujata
sujata on 26 Jan 2021
Edited: Jan on 26 Jan 2021
So I have a vector e.g
P = [0.9 0.8] 1x2 vector
My outcome has to become Q =
0.9000 0.8000 0 0 0
0 0.9000 0.8000 0 0
0 0 0.9000 0.8000 0
0 0 0 0.9000 0.8000
So basically the row represent a year forecast, and the number is a pattern that has to be applied.
so i have a bit difficulty transforming this P vector into such a format. i.e that whenever the vector is moved one column that it has to add a zero column or something. I am trying to do this without for loops obviously.
best

Answers (1)

Jan
Jan on 26 Jan 2021
Edited: Jan on 26 Jan 2021
P = [0.9, 0.8];
n = 4;
m = n*n + n;
Q = zeros(n, n + 1);
Q( 1:1+n:m) = P(1);
Q(n+1:1+n:m) = P(2);
or:
Q = reshape(repmat([P(1), zeros(1, n-1), P(2)], 1, n), n, []);
I assume the first one is more efficient.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!