Arrays in Scilab

Arrays in Scilab are sequences of elements of a specific type. They are fundamental data structures and are used extensively in scientific computing and numerical analysis.

// Here we create an array 'a' that will hold exactly 5 integers.
// By default, an array is zero-valued in Scilab.
a = zeros(1, 5);
disp("emp:", a);

// We can set a value at an index using the array(index) = value syntax,
// and get a value with array(index).
a(5) = 100;
disp("set:", a);
disp("get:", a(5));

// The length function returns the length of an array.
disp("len:", length(a));

// Use this syntax to declare and initialize an array in one line.
b = [1, 2, 3, 4, 5];
disp("dcl:", b);

// In Scilab, you can't use the ... syntax like in Go to let the compiler
// count the elements. You need to specify the elements explicitly.

// If you want to create an array with specific values at certain indices,
// you can do it like this:
c = [100, 0, 0, 400, 500];
disp("idx:", c);

// Array types in Scilab can be multi-dimensional by default.
// Here's how to create a 2x3 array:
twoD = zeros(2, 3);
for i = 1:2
    for j = 1:3
        twoD(i, j) = i + j - 2;
    end
end
disp("2d: ", twoD);

// You can create and initialize multi-dimensional arrays at once too.
twoD = [1, 2, 3; 1, 2, 3];
disp("2d: ", twoD);

When you run this script, you should see output similar to this:

emp: 0. 0. 0. 0. 0.
set: 0. 0. 0. 0. 100.
get: 100.
len: 5.
dcl: 1. 2. 3. 4. 5.
idx: 100. 0. 0. 400. 500.
2d:
   0.   1.   2.
   1.   2.   3.
2d:
   1.   2.   3.
   1.   2.   3.

Note that arrays in Scilab are displayed differently from some other languages. They are typically shown with periods after each number to indicate they are floating-point values, even if they were defined as integers.

Also, Scilab uses 1-based indexing, unlike many other programming languages which use 0-based indexing. This means the first element of an array is at index 1, not 0.

Scilab’s arrays are quite flexible and powerful, especially for numerical computations. They can be easily resized and manipulated using various built-in functions, making them a cornerstone of scientific computing in Scilab.