Iterate Multi-Dimensional Array with Nested Foreach Statement
If you want to iterate over every item in the array as if it were a flattened array, you can just do:
foreach (int i in array) {
Console.Write(i);
}
which would print
123456
If you want to be able to know the x and y indexes as well, you'll need to do:
for (int x = 0; x < array.GetLength(0); x += 1) {
for (int y = 0; y < array.GetLength(1); y += 1) {
Console.Write(array[x, y]);
}
}
Alternatively you could use a jagged array instead (an array of arrays):
int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
foreach (int i in subArray) {
Console.Write(i);
}
}
or
int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
for (int k = 0; k < array[j].Length; k += 1) {
Console.Write(array[j][k]);
}
}
Foreach with multidimensional arrays in Java
An array of N dimensions is really an array of (N-1)-dimensional arrays. Therefore, when we iterate over an array of N dimensions, we are iterating over all of its constituent (N-1)-dimensional arrays, as indicated.
For example, consider a 2-dimensional array:
int[][] array = {{1,2,3}, {4,5,6}};
This is really an array of 1-dimensional arrays: {1,2,3}
and {4,5,6}
.
An efficient way to iterate over a multidimensional array?
You're already using numpy
. numpy's std()
function takes an axis
argument that tells it what axis you want it to operate on (in this case the zeroth axis). Because this offloads the calculation to numpy's C-backend (and possibly using SIMD optimizations for your processor that vectorize a lot of operations), it's so much faster than iterating. Another time-consuming operation in your code is when you append to stddev_arr
. Appending to numpy arrays is slow because the entire array is copied into new memory before the new element is added. Now you already know how big that array needs to be, so you might as well preallocate it.
a = np.arange(32).reshape(2, 4, 4)
stdev = np.std(a, axis=0)
This gives a 4x4
array
array([[8., 8., 8., 8.],
[8., 8., 8., 8.],
[8., 8., 8., 8.],
[8., 8., 8., 8.]])
To flatten this into a 1D array, do flat_stdev = stdev.flatten()
.
Comparing the execution times:
# Using only numpy
def fun1(arr):
return np.std(arr, axis=0).flatten()
# Your function
def fun2(arr):
stddev_arr = np.array([])
for i in range(arr.shape[1]):
for j in range(arr.shape[2]):
pixel = arr[0:,i,j]
stddev = np.std(pixel)
stddev_arr = np.append(stddev_arr, stddev)
return stddev_arr
# Your function, but pre-allocating stddev_arr
def fun3(arr):
stddev_arr = np.zeros((arr.shape[1] * arr.shape[2],))
x = 0
for i in range(arr.shape[1]):
for j in range(arr.shape[2]):
pixel = arr[0:,i,j]
stddev = np.std(pixel)
stddev_arr[x] = stddev
x += 1
return stddev_arr
First, let's make sure all these functions are equivalent:
a = np.random.random((3, 10, 10))
assert np.all(fun1(a) == fun2(a))
assert np.all(fun1(a) == fun3(a))
Yup, all give the same result. Now, let's try with a bigger array.
a = np.random.random((3, 100, 100))
x = timeit.timeit('fun1(a)', setup='from __main__ import fun1, a', number=10)
# x: 0.003302899989648722
y = timeit.timeit('fun2(a)', setup='from __main__ import fun2, a', number=10)
# y: 5.495519500007504
z = timeit.timeit('fun3(a)', setup='from __main__ import fun3, a', number=10)
# z: 3.6250679999939166
Wow! We get a ~1.5x speedup just by preallocating.
Even more wow: using numpy's std()
with the axis
argument gives a > 1000x speedup, and this is just for the 100x100
array! With bigger arrays, you can expect to see even bigger speedup.
Iterating a Multidimensional Array in TypeScript
const data = [
null,
[
null,
{
"deviceID": 1,
"deviceType": 1,
"updateFrequency": 1,
"lastUpdate": 1557679860000,
"payload": [
22,
31,
32
.... rest of your array data
Then you can create a Util class:
class Utils {
public flatten(arr: any[]): any[] {
// in node 11+, FF and Crome:
// return arr.flat();
return [].concat(...arr);
}
// Use if you want to exclude null, undefined
// or any falsey value from final array
public compact(arr: any[]): any[] {
return arr.filter(Boolean);
}
}
const utils = new Utils();
const tempDeviceList = utils.compact(utils.flatten(data));
console.log(tempDeviceList[1]); // {deviceID: 2....
console.log(tempDeviceList.length); // 16
Read more about the new Array.prototype.flat()
How does foreach loop works with 2d array?
2D string array is not optimal choice for your task ("build a store with car"). c# is object-oriented language, so you can have a class for Car, and a class for Store with list of cars - easy to build, maintain, modify:
public class Car
{
public string Brand { get; set; }
public double Price { get; set; }
public int Year { get; set; } // new Car property
}
public class CarStore
{
public IList<Car> Cars { get; } = new List<Car>();
}
then use for
loop or foreach
- both will work
public static void Main()
{
var store = new CarStore
{
Cars =
{
new Car { Brand = "Ford", Year = 2021, Price = 120000 },
new Car { Brand = "Chevrolet", Year = 2020, Price = 100000 },
}
};
foreach(var car in store.Cars)
{
Console.WriteLine(car.Price.ToString("C"));
}
// new car arrived:
store.Cars.Add(new Car { Brand = "Rolls-Royce", Year = 2022, Price = 1_000_000 });
}
Related Topics
Pass a Js Variable to a PHP Variable
MySQL_Fetch_Array Return Only One Row
PHP Short Hash Like Url-Shortening Websites
Anonymous Recursive PHP Functions
How to Set the Default Value of a Timestamp Column to the Current Timestamp With Laravel Migrations
Convert String into Slug With Single-Hyphen Delimiters Only
Set Pdo to Throw Exceptions by Default
How to Delete All Cookies of My Website in PHP
How to Change PHP Version in Htaccess in Server
PHP Domdocument Errors/Warnings on Html5-Tags
File_Get_Contents =≫ PHP Fatal Error: Allowed Memory Exhausted
Using Simplexml to Create an Xml Object from Scratch
Explode String by One or More Spaces or Tabs
How to Set Upload_Max_Filesize in .Htaccess