Structs in Scilab
Our first example explains how to use structs to group related data together.
// Define the struct type 'person' with 'name' and 'age' fields
person = struct("name", "age");
// Function to construct a new person with a specified name
function p = newPerson(name)
p = struct("name", name, "age", 42);
endfunction
function main()
// Create a new struct
disp(struct("name", "Bob", "age", 20));
// Name the fields when initializing a struct
disp(struct("name", "Alice", "age", 30));
// Omitted fields will be zero-valued (or empty in Scilab's case)
disp(struct("name", "Fred"));
// Using a pointer (i.e., referencing the struct dictionary)
Ann = struct("name", "Ann", "age", 40);
disp(Ann);
// Using the constructor function
Jon = newPerson("Jon");
disp(Jon);
// Access struct fields with dot notation
s = struct("name", "Sean", "age", 50);
disp(s.name);
// Use dots with struct pointers (direct referencing in Scilab)
sp = s;
disp(sp.age);
// Modify struct fields
sp.age = 51;
disp(sp.age);
// Anonymous struct type for single value usage
dog = struct("name", "Rex", "isGood", %t);
disp(dog);
endfunction
main();
In this example, we’ve defined a person
struct type with name
and age
fields. We then created functions to construct a new person and demonstrated various ways to work with structs, including initializing, accessing, and modifying fields.
To execute this code, just copy it into a Scilab script file (e.g., structs.sce
) and run it in the Scilab environment.
Scilab handles structs as dictionaries, and you can directly manipulate them using dot notation for accessing and updating fields. Note that, unlike some languages, Scilab does not have direct support for pointers, but we can simulate references using variable assignments.