Notable differences from other languages¶
Although the syntax of Julia may seem familiar to MATLAB users, Julia is not a MATLAB clone. There are important syntactic and functional differences between the two. The following are some notable differences in Julia that may confuse users who are used to MATLAB.
Differences from MATLAB¶
- array indices in Julia are specified in square brackets: A[i,j].
In [ ]:
Pkg.add(["LinearAlgebra"])
In [ ]:
A = [1 2 3; 4 5 6; 7 8 9]
i = 2
j = 3
element = A[i, j]
println(element)
- When an array in Julia is assigned to another variable, it is not copied. After assigning A = B, changing the elements of B will cause them to change in A.
In [ ]:
B = [1, 2, 3]
A = B
B[1] = 10
println(A)
- In Julia, values passed to a function are not copied. If the function changes the array, these changes will be visible to the caller.
In [ ]:
function modify_array(arr)
arr[1] = 100
end
A = [1, 2, 3]
modify_array(A)
println(A)
- In Julia, arrays are not enlarged automatically when using the assignment operator. Whereas in MATLAB you can create an array a = [0 0 0 0 3.2] using the expression a(4) = 3.2 and expand it to a = [0 0 0 0 3.2 7] using the expression a(5) = 7, in Julia the corresponding operator a[5] = 7 gives an error if the length of a is less than 5 or if the name a is used for the first time in this operator. Julia has push! and append! functions that allow you to increment objects of type Vector much more efficiently than a(end+1) = val in MATLAB.
In [ ]:
A = [1, 2, 3]
push!(A, 4)
println(A)
B = [5, 6, 7]
append!(B, [8, 9])
println(B)
- The imaginary unit sqrt(-1) is represented in Julia by the constant im, not i or j as in MATLAB.
In [ ]:
z = 2 + 3im
println(z)
println("Действительная часть: ", real(z))
println("Мнимая часть: ", imag(z))
- In Julia, numeric literals without a decimal separator (e.g., 42) create integers rather than floating point numbers. As a result, some operations may produce an out-of-area error if they expect a floating-point number. For example, julia> a = -1; 2^a will produce such an error because the result is not an integer (see the FAQ on out-of-area errors for details).
In [ ]:
a = 42 # целое число
b = 42.0 # число с плавающей запятой
c = float(42) # явное преобразование к типу Float64
println(a)
println(b)
println(c)
- If multiple values are to be returned or assigned in Julia, tuples are used, e.g. (a, b) = (1, 2) or a, b = 1, 2. Julia does not have the nargout function, which is often used in MATLAB to perform additional actions depending on the number of values returned. Optional and named arguments can be used for similar purposes.
In [ ]:
function get_values()
return 1, 2
end
x, y = get_values()
println(x)
println(y)
- Julia has true one-dimensional arrays. The column vectors are of size N, not Nx1. For example, the rand(N) expression creates a one-dimensional array.
In [ ]:
v = [1, 2, 3] # одномерный массив
Out[0]:
- In Julia, the construct [x,y,z] always creates an array containing three elements: x, y, and z.- To concatenate along the first ("vertical") dimension, call the vcat(x,y,z) function or use a semicolon ([x; y; z]) as a delimiter.- To concatenate along the second ("horizontal") dimension, call the hcat(x,y,z) function or use a space ([x y z]) as a separator.- To create block matrices (with concatenation along the first two dimensions), call the hvcat function or combine spaces and semicolons as delimiters ([a b; c d]).
In [ ]:
A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]
D = vcat(A, B, C) # вертикальная конкатенация
println(D)
E = hcat(A, B, C) # горизонтальная конкатенация
println(E)
F = [A; B; C] # разделитель ";"
println(F)
G = [A B C] # разделитель пробел
println(G)
- In Julia, the constructs a:b and a:b :c create AbstractRange objects. To create a complete vector, as in MATLAB, use the collect(a:b) method. However, it is usually not necessary to call collect. An AbstractRange object behaves like a regular array in most cases, but it is more efficient due to the "lazy" calculation of values. This pattern of creating special objects instead of full arrays is used frequently, including with functions such as range and iterators such as enumerate and zip. Special objects can generally be used like regular arrays.
In [ ]:
range = 1:5
vector = collect(range)
println(vector)
- Functions in Julia return the result of calculating the last expression or an expression with the return keyword. It is not necessary to list the names of the returned variables in the function definition (see the Return keyword section for details).
In [ ]:
function sum(x, y)
x + y
end
result = sum(2, 3)
println(result)
- In Julia, when calling a function without arguments, you must use parentheses, e.g. rand().
In [ ]:
function example()
println("Функция без аргументов")
end
example()
- In Julia, it is not recommended to put semicolons at the end of expressions. The results of expressions are not displayed automatically (except on the interactive command line), so there is no need to end lines of code with semicolons. You can use the println function or the @printf macro to display certain data on the screen.
In [ ]:
a = 2
b = 3
c = a + b
println(c)
- In Julia, if A and B are arrays, logical comparison operations such as A == B do not return an array of logical values. Instead, use A .== B or similar expressions for other logical operators such as < and >.
In [ ]:
A = [1, 2, 3]
B = [2, 2, 3]
result = A .== B
println(result)
- In Julia, the operators &, |, and ⊻ (xor) are bitwise, just as and, or, and, or, and xor in MATLAB, respectively. Their precedence is the same as that of bitwise operators in Python (but not as in C). They can be applied to scalar values or element-by-element to arrays, and can also be used to combine logical arrays. However, note the difference in the order of operations: parentheses may be required (for example, to select elements of A equal to 1 or 2, use the expression (A .== 1) .| (A .== 2)).
In [ ]:
a = 5
b = 3
result = a & b
println(result)
A = [true, false, true]
B = [false, true, true]
result = A .& B
println(result)
- In Julia, the elements of a collection can be passed to a function as arguments using the extension operator (splat operator) ..., e.g. xs=[1,2]; f(xs...).
In [ ]:
function sum_elements(x, y, z)
return x + y + z
end
values = [1, 2, 3]
result = sum_elements(values...)
println(result)
- The svd function in Julia returns singular values as a vector rather than a dense diagonal matrix.
In [ ]:
using LinearAlgebra
A = [1 2; 3 4]
U, S, V = svd(A)
println(S)
- In Julia, the ... is not used to continue lines of code. Instead, an incomplete expression is automatically continued on the next line.
In [ ]:
a = 2 +
3
println(a)
- Structures (struct) in Julia do not support dynamic addition of fields at runtime, unlike classes (class) in MATLAB. Use Dict instead. Dictionaries in Julia are not ordered.
In [ ]:
struct MyStruct1
field1::Int
end
s = MyStruct1(10)
println(s.field1)
# Используем словарь для добавления поля field2
s_dict = Dict(:field1 => s.field1, :field2 => 20)
println(s_dict[:field2])
- In Julia, each module has its own global area or namespace, while in MATLAB there is only one global area.
In [ ]:
module MyModule
global_var = 10
function my_function()
println(global_var)
end
end
MyModule.my_function()
- In MATLAB, an idiomatic way to remove unnecessary values is to use logical indexing, as in the expression x(x>3) or the operator x(x>3) = [] to change x in place. In Julia, higher-order functions filter and filter! are provided for this purpose, allowing the expressions filter(z->z>3, x) and filter!(z->z>3, x) to be used as alternatives for x[x.>3] and x = x[x.>3]. The filter! function allows you to resort to temporary arrays less frequently.
In [ ]:
A = [1, 2, 3, 4, 5]
filtered_A = filter(x -> x > 3, A)
println(filtered_A)
filter!(x -> x > 3, A)
println(A)
- Extracting (or "dereferencing") all elements of a cell array, such as vertcat(A{:}) in MATLAB, is written in Julia using an expansion operator (splat operator), such as vcat(A...).
In [ ]:
A = [1, 2]
B = [3, 4]
C = [5, 6]
array_of_arrays = [A, B, C]
concatenated_array = vcat(array_of_arrays...)
println(concatenated_array)
- In Julia, the adjoint function performs conjugate transpose; in MATLAB, adjoint provides the adjoint matrix (classical adjoint), that is, it performs transpose of the matrix of algebraic complements.
In [ ]:
A = [1+2im 3+4im]
adj_A = adjoint(A)
println(adj_A)
- In Julia, the expression (a ^ b ^ c) is evaluated as a^ (b^c), while in MATLAB it is evaluated as (a ^ b) ^ c.
In [ ]:
a = 3
b = 2
c = 3
result = a^(b^c)
println(result)
Differences from Python¶
- In Julia, blocks for, if, while, etc. end with the end keyword, not indented as in Python. There is no pass keyword.
In [ ]:
for i in 1:5
println(i)
end
- In Julia, strings are denoted by double quotes, three pairs of double quotes are used for multi-line texts. Also, single quotes are used for characters.
In [ ]:
str1 = "Hello, World!"
str2 = """Это много-
строчный текст."""
char1 = 'c'
Out[0]:
- Julia uses the * operator to concatenate strings, not + as in Python. The ^ operator is used to repeat strings, not *.
In [ ]:
str1 = "Hello, "
str2 = "World!"
concatenated_str = str1 * str2
repeated_str = str2 ^ 3
println(concatenated_str)
println(repeated_str)
- In Julia, lists correspond to the type Vector{Any} or the more general type Vector{T}, where T is some element type. More efficient arrays, like NumPy arrays, can be represented by Array{T} arrays, where T is a specific element type.
In [ ]:
list1 = Any[1, "two", 3.0]
list2 = Vector{Int}(undef, 5)
array1 = Array{Int}(undef, 3, 3)
Out[0]:
- Indexing of arrays in Julia starts at one, unlike Python where indexing starts at zero.
In [ ]:
array = [1, 2, 3, 4, 5]
println(array[1]) # Выведет 1
- When indexing slices in Julia, the last element is included, unlike in Python. a[2:3] in Julia is equivalent to a[1:3] in Python.
In [ ]:
array = [1, 2, 3, 4, 5]
println(array[2:3]) # Выведет [2, 3]
- AbstractArrays with arbitrary indices are allowed in Julia. Negative indices, which have a special meaning in Python, are written in Julia as a[end] and a[end-1].
In [ ]:
array = [1, 2, 3, 4, 5]
println(array[end]) # Выведет 5
println(array[end - 1]) # Выведет 4
- The end keyword is used in Julia to index to the last element. x[1:] in Python is equivalent to x[2:end] in Julia.
In [ ]:
array = [1, 2, 3, 4, 5]
println(array[2:end]) # Выведет [2, 3, 4, 5]
- In Julia, range indexing has the format x[start:step:stop], while in Python it is x[start:(stop+1):step]. Therefore x[0:10:2] in Python is equivalent to x[1:2:10] in Julia.
In [ ]:
array = [1, 2, 3, 4, 5]
println(array[1:2:end]) # Выведет [1, 3, 5]
- There is no string continuation syntax in Julia. If a string contains a complete expression, it is considered complete. Otherwise, the string is continued. You can use parentheses to continue an expression.
In [ ]:
a = (
1 + 2 +
3
)
println(a) # Выведет 6
- In Julia, arrays are expanded by columns, while NumPy arrays are expanded by rows. When looping arrays in Julia, the loop order must be reversed compared to NumPy.
In [ ]:
A = [1 2; 3 4; 5 6]
for j in 1:size(A, 2), i in 1:size(A, 1)
println(A[i, j])
end
- In Julia, the default values of function arguments are evaluated at each method call, unlike in Python, where values are evaluated only when the function is defined.
In [ ]:
function f(x = rand())
return x
end;
In [ ]:
println(f()) # Выполните ячейку несколько раз
- In Julia, named arguments must be passed with names, unlike in Python.
In [ ]:
function foo(a; b = 1, c = 2)
return a + b + c
end
println(foo(10, b = 3, c = 4)) # Выведет 17, нельзя вызывать как println(foo(10, 3, 4)), в случае с Python
- In Julia, the Int type corresponds to a machine integer type (Int32 or Int64), while in Python int can be of arbitrary length.
In [ ]:
x = Int64(2) ^ Int64(64)
println(x) # Выведет 0
- The imaginary unit in Julia is represented by the constant im, while Python uses j.
In [ ]:
println(2im) # Выведет 0 + 2im
- In Julia, the degree operator is denoted by ^, not ** as in Python.
In [ ]:
println(2 ^ 3) # Выведет 8
- The empty value in Julia is denoted by the constant nothing of type Nothing, while Python uses a None object of type NoneType.
In [ ]:
x = nothing
println(x) # Выведет nothing
- In Julia, the * operator performs matrix operation while in Python it performs element-by-element multiplication. In Julia, the .* operator is used for element-by-element multiplication.
In [ ]:
A = [1 2;
3 4]
B = [5 6;
7 8]
println(A * B) # Выведет матрицу, [19 22; 43 50]
println(A .* B) # Выведет матрицу, [5 12; 21 32]
- In Julia, the ' operator returns the conjugate vector, while the .T transpose operator in Python returns the original vector.
In [ ]:
x = [1 2 3]
println(x') # Выведет [1; 2; 3]
- In Julia, a function can have several concrete implementations (methods) that are chosen based on the types of arguments. In Python, a function has a single implementation, and polymorphism is not supported.
In [ ]:
function square(x::Number)
return x * x
end
function square(x::String)
return string(x, x)
end
println(square(2)) # Выведет 4
println(square("hello")) # Выведет "hellohello"
- In Julia, there are no classes; instead, structures are used, which contain only data but not methods.
In [ ]:
struct MyStruct
x::Int
y::Float64
end
function f(obj::MyStruct, z)
return obj.x + obj.y + z
end
my_obj = MyStruct(1, 2.5)
println(f(my_obj, 3.5)) # Выведет 7.0
- Calling a method of a class instance in Python corresponds to calling a function in Julia.
In [ ]:
struct MyType
x::Int
end
function f(obj::MyType, y)
return obj.x + y
end
my_obj = MyType(10)
println(f(my_obj, 5)) # Выведет 15
- A structure in Julia can have only one abstract supertype, while Python classes can inherit from multiple superclasses.
In [ ]:
abstract type Animal end
struct Dog <: Animal
name::String
end
struct Cat <: Animal
name::String
end
dog = Dog("Buddy")
cat = Cat("Whiskers");
- In Julia, a ternary operator is written as x > 0 ? 1 : -1, while Python uses the conditional expression 1 if x > 0 else -1.
In [ ]:
x = 10
result = x > 0 ? 1 : -1
println(result) # Выведет 1
- Julia handles exceptions using the try-catch-finally construct, unlike Python which uses try-except-finally.
In [ ]:
try
# Код, который может вызвать исключение
catch ex
# Обработка исключения
finally
# Выполнение кода, который будет выполнен в любом случае
end
Conclusion:¶
This example has demonstrated the main syntactic and functional differences that distinguish Julia from Matlab and Python.