Search code examples
matlabfor-loopwhile-loopsqrt

How to create triangular matrix that varies with row indices and data?


I need to calculate some points. First I am going to explain the problem. I have a vector of data named X.

X=[20 50 100 150 200 300]

I need to generate some data and I am using this method:

a11=sqrt(1-0/20)-sqrt(1-20/20);

That is the result for 20 or X(1). Then I need to calculate this:

a21=sqrt(1-0/50)-sqrt(1-20/50);
a22=sqrt(1-20/50)-sqrt(1-50/50);

This is the result for 50 or X(2).

For X(3) i need a31,a32,a33, for X(4) i need a41,a42,a43,a44 ... Then I need to put that values in matrix in respect to X.

The matrix should look like:

20 a11
50 a21 a22
100 a31 a32 a33
150 a41 a42 a43 a44
.
.
.

Thank you.


Solution

  • Just to add a loop-free solution:

    X = [20 50 100 150 200 300];
    X2 = [0 X];
    outmat = [X.', tril(-diff(sqrt(1-(1./X).'*X2),1,2))];
    

    The non-trivial part of the output matrix works like this: it first computes the sqrt(1-X(k)/X(l)) kinds of values in a matrix, essentially creating the matrix as a dyadic product of X and X2 (the latter is X extended with a leading 0 element). Then, we compute the diff of this matrix along its second dimension: be careful that the second input parameter of diff gives the order of the numerical derivative. Then we cut out the lower-triangular part with tril.