Note that there are some explanatory texts on larger screens.

plurals
  1. POc# assign 1 dimensional array to 2 dimensional array with shifting values
    primarykey
    data
    text
    <p>I have a vector (1D array) of double values, say X. I need to copy this vector of values into a matrix (2D array), say Y, such that the first row of Y is the same as X transposed, the second row is the same as X shifted one value to the left, the third row of Y is the same as X shifted two values to the left and so on.</p> <p>For example,</p> <pre><code>X = { 1.0, 2.0. 3.0, 4.0, 5.0 } </code></pre> <p>and I need </p> <pre><code>Y = 1.0 2.0 3.0 4.0 5.0 2.0 3.0 4.0 5.0 0.0 3.0 4.0 5.0 0.0 0.0 4.0 5.0 0.0 0.0 0.0 5.0 0.0 0.0 0.0 0.0 </code></pre> <p>Some time ago Mathew Finlay posted code for copying 1D array to a 2D array for value types. I have modified the code as follows:</p> <pre><code>for (int targetRow = 0; targetRow &lt; N; targetRow++) { Buffer.BlockCopy ( X, // 1D source array 0, // source array offset Y, // 2D target (destination) array targetRow * Y.GetLength(targetRow) * sizeof(double), // target array offset X.Length * sizeof(double) // count ); } </code></pre> <p>I am not sure if this will do the trick and more importantly, whether this is the best way of doing this. This is part of a larger code and this part needs to be fast and efficient as the vector X and the matrix Y can get very large.</p> <p>Also, to complicate things a bit more, I may sometines not require the full length (all the values) of vector X but only part of it so the matrix Y could be N x M where M &lt;= N. I am not sure how to handle this in the code above.</p> <p>Thank you in advance for any help or suggestions you may be able to provide.</p> <p>EDIT: For those interested, here are some performance results.</p> <p>I ran some speed tests on the two types of code suggested here (looping and Buffer.BlockCopy) and the results surprised me. I will designate the Buffer.BlockCopy as BC and looping as L. For 10x10 matrix BC = 00:00:00.0000017 and L = 00:00:00.0000030. For 100x100 matrix BC = 00:00:00.0000293 and L = 00:00:00.0000710. Finally, for 1000x1000 matrix BC = 00:00:00.0065340 and L = 00:00:00.0138396. So the Buffer.Block copy seems to outperform looping even for small matrices. I ran this on a Win 7 Ultimate (64) machine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload