有人可以帮助我将2d数组转换为1d数组吗? 2d数组随机编译。我也是C#的新手,是的,我为我的英语感到抱歉) 谢谢!
Random rnd = new Random();
int[,] lala = new int[5, 6];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 6; j++)
{
lala[i, j] = rnd.Next(1, 10);
Console.Write(lala[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
int i, j;
int[] b = new int[30];
int k = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 6; j++)
{
b[k++] = lala[i, j];
}
}
for (i = 0; i < 5 * 6; i++)
{
Console.WriteLine(b[i] + " ");
}
Console.ReadKey();
答案 0 :(得分:0)
如果您只想以某种方式将2D数组的值放入1D中,这是一种方法
int upper1 = 5;
int upper2 = 6;
int[,] twoD = new int[upper1, upper2];
// fill array
int[] oneD = new int[upper1 * upper2];
int idx = -1;
for (int i = 0; i < upper1; i++)
{
for (int j = 0; j < upper2; j++)
{
oneD[++idx] = twoD[i,j];
}
}
答案 1 :(得分:0)
Output audio: 2048 samples, audioFreq: 44100, audioFs: 50000.0
Fetching 98304 IQ samples from SDR #0
...
Fetching 98304 IQ samples from SDR #0
decRate: 12, newFs : 200000.0, dec_audio: 4
Output audio: 2048 samples, audioFreq: 44100, audioFs: 50000.0
Fetching 98304 IQ samples from SDR #0
[ 627.05045796 1835.36815837 3381.16496121 ... 401.43836645
-1156.07050642 -1291.0900775 ]
float64
From cffi callback <function _StreamBase.__init__.<locals>.callback_ptr at 0x10eabbea0>:
Traceback (most recent call last):
File "/Users/user/.local/lib/python3.6/site-packages/sounddevice.py", line 741, in callback_ptr
return _wrap_callback(callback, data, frames, time, status)
File "/Users/user/.local/lib/python3.6/site-packages/sounddevice.py", line 2517, in _wrap_callback
decRate: 12, newFs : 200000.0, dec_audio: 4
Output audio: 2048 samples, audioFreq: 44100, audioFs: 50000.0
callback(*args)
File "rtl-fm-cont.py", line 120, in audio_callback
outdata[:] = data
ValueError: could not broadcast input array from shape (2048) into shape (2048,1)
Fetching 98304 IQ samples from SDR #0
decRate: 12, newFs : 200000.0, dec_audio: 4
Output audio: 2048 samples, audioFreq: 44100, audioFs: 50000.0
您的错误是在'i'和'j'变量声明中。我建议您在要使用的上下文中声明一个变量,而不要在该上下文之外重用它。
答案 2 :(得分:0)
使用Linq扩展方法Cast
和ToArray
的快速单行代码即可解决问题。我相信Cast
只是将数组中的所有项目(从所有维度中提取),将其转换为指定的类型,然后以IEnumerable
的形式返回(ToArray
然后转换为数组) :
int[] oneDimensionalArray = twoDimensionalArray.Cast<int>().ToArray();
另一种实现方法是使用foreach
循环,该循环将遍历二维数组的两个维度:
int index = 0;
foreach (var item in twoDimensionalArray)
{
oneDimensionalArray[index++] = item;
}
代码示例:
var rnd = new Random();
var rowCount = 10;
var colCount = 10;
// Populate two dimensional array. You could also use this "double for loop" structure
// to read the multi-dimensional array and then populate the one dimensional array.
var twoD = new int[rowCount, colCount];
for (var row = 0; row < rowCount; row++)
{
for (var col = 0; col < colCount; col++)
{
twoD[row, col] = rnd.Next();
}
}
// Populate one dimensional array with a foreach loop. Use a separate
// hold the index value for the one dimentional array
var oneD = new int[rowCount * colCount];
var index = 0;
foreach (var item in twoD)
{
oneD[index++] = item;
}