# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.3.3 # kernelspec: # display_name: Julia 1.6.2 # language: julia # name: julia-1.6 # --- # #### Julia Tutorial: Vectors # Vectors in Julia differ a bit from Matlab. # In Matlab, everything is an array, including vectors (and even scalars). # In Julia, there are distinct data types for scalars, vectors, rowvectors, and 1D arrays. # This notebook illustrates the differences. # Jeff Fessler, University of Michigan # 2017-07-24, original # 2020-08-05, Julia 1.5.0 # 2021-08-23, Julia 1.6.2 # #### Scalars, Vectors, Arrays a = 4 # this is a scalar b1 = [4] # this is a Vector with one element b2 = reshape([4], 1, 1) # here is a 1×1 Array b3 = reshape([4], 1, 1, 1) # here is a 1×1×1 Array a==b1, b1==b2, a==b2, b2==b3 # in Julia these all differ! (in Matlab they are the same) # #### Vectors and Transpose c = [4 5 6] # this construction (with just spaces) makes a 1×3 Array d = [4, 5, 6] # this construction (using commas) makes a 1D Vector e = [4; 5; 6] # so does this construction, whereas in Matlab the "," and ";" work differently d' # the transpose of a Vector is slightly different than a 1×N array! This is subtle! d' == c # nevertheless, the values are the same... (d')' # Transposing back gives a vector again (not a N×1 array) d==e, d'==c, (c')'==d' # These are all true, as expected, despite the adjoint type. c==d, c==e, c'==d, (d')'==c' # These are all false. c * c' # "inner product" of a 1×3 Array with a 3×1 Array returns a 1×1 Array, not a scalar d' * d # This inner product of an Adjoint Vector with a Vector returns a scalar vec(c) # how to make a vector from an array c[:] # Here is another way (but it uses more memory than vec) # ### Call by reference # Julia uses call-by-reference (not value), like C/C++, unlike Matlab! A = zeros(2); B = A; B[1] = 7; # B is the same "pointer" so this changes A @show A; A = zeros(2); B = A .+ 2; B[1] = 7; # here B is different so this does not change A @show A; A = B = zeros(2); B[1] = 7; # changes A because B and A point to same data @show A; A = B = zeros(2); A[1] = 7; # changes B for the same reason @show B; # To avoid this issue, one can use `copy`. # It is only needed rarely though. A = zeros(2); B = copy(A); B[1] = 7; # B here uses different memory than A @show A; # here it is unchanged