# top//a side-by-side reference sheet//
sheet one: [#grammar-invocation grammar and invocation] | [#var-expr variables and expressions] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regexes] | [#dates-time dates and time] | [#tuples tuples] | [#arrays arrays] | [#arithmetic-sequences arithmetic sequences] | [#two-d-arrays 2d arrays] | [#three-d-arrays 3d arrays] | [#dictionaries dictionaries] | [#functions functions] | [#execution-control execution control] | [#file-handle file handles] | [#directories directories] | [#processes-environment processes and environment] | [#libraries-namespaces libraries and namespaces] | [#reflection reflection] | [#debugging debugging]
sheet two]: tables] | import and export] | relational algebra] | aggregation]
vectors] | matrices] | sparse matrices] | optimization] | polynomials] | descriptive statistics] | distributions] | linear regression] | statistical tests] | time series] | fast fourier transform] | clustering] | images] | sound]
bar charts] | scatter plots] | line charts] | surface charts] | chart options]
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# version-used[#version-used-note version used]||##gray|//MATLAB 8.3//## _ _ ##gray|//Octave 3.8//##||##gray|//3.1//##||##gray|//Python 2.7//## _ ##gray|//NumPy 1.7//## _ ##gray|//SciPy 0.13//## _ ##gray|//Pandas 0.12//## _ ##gray|//Matplotlib 1.3//##||##gray|//0.4//##|| ||# show-version[#show-version-note show version]||$ matlab -nojvm -nodisplay -r ‘exit’ _ _ $ octave @@–version@@||$ R @@–version@@||sys.version _ np.@@version@@ _ sp.@@version@@ _ mpl.@@version@@||$ julia @@–@@version|| ||# implicit-prologue[#implicit-prologue-note implicit prologue]||##gray|//none//##||install.packages(‘ggplot2’) _ library(‘ggplot2’)||import sys, os, re, math _ import numpy as np _ import scipy as sp _ import scipy.stats as stats _ import pandas as pd _ import matplotlib as mpl _ import matplotlib.pyplot as plt|| || ||||||||||~ # grammar-invocation[#grammar-invocation-note grammar and invocation]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# interpreter[#interpreter-note interpreter] _ @< >@||$ cat @@>>@@foo.m _ 1 + 1 _ exit _ _ $ matlab -nojvm -nodisplay -r “run(‘foo.m’)” _ _ $ octave foo.m||$ cat @@>>@@foo.r _ 1 + 1 _ _ $ Rscript foo.r _ _ $ R -f foo.r||$ cat @@>>@@foo.py _ print(1 + 1) _ _ $ python foo.py||$ cat @@>>@@foo.jl _ println(1 + 1) _ _ $ julia foo.jl|| ||# repl[#repl-note repl] _ @< >@||$ matlab -nojvm -nodisplay _ _ $ octave||$ R||$ python||$ julia|| ||# cmd-line-program[#cmd-line-program-note command line program]||$ matlab -nojvm -nodisplay -r ‘disp(1 + 1); exit’ _ _ $ octave @@–@@silent @@–@@eval ‘1 + 1’||$ Rscript -e ‘print(“hi”)’||python -c ‘print(“hi”)’||$ julia -e ‘println(“hi”)’|| ||# block-delimiters[#block-delimiters-note block delimiters]||function end _ if elseif else end _ while end _ for end||{ }||##gray|//offside rule//##|| || ||# stmt-separator[#stmt-separator-note statement separator]||; ##gray|//or newline//## _ _ ##gray|//Newlines not separators after three dots:// @@…@@## _ _ ##gray|//Output is suppressed when lines end with a semicolon.//##||; ##gray|//or sometimes newline//## _ _ ##gray|//Newlines not separators inside (), [], {}, ‘‘, ““, or after binary operator.//##||##gray|//newline or ; _ _ Newlines not separators inside (), [], {}, triple quote literals, or after backslash: \//##|| || ||# eol-comment[#eol-comment-note end-of-line comment] _ @< >@||1 + 1 ##gray|% addition##||1 + 1 ##gray|# addition##||1 + 1 ##gray|# addition##||1 + 1 ##gray|# addition##|| ||||||||||~ # var-expr[#var-expr-note variables and expressions]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# assignment[#assignment-note assignment]||i = 3||i = 3 _ i <- 3 _ 3 -> i _ assign(“i”, 3)||i = 3||i = 3|| ||# parallel-assignment[#parallel-assignment-note parallel assignment]|| || || || || ||# swap[#swap-note swap]|| || || || || ||# compound-assignment[#compound-assignment-note compound assignment] _ ##gray|//arithmetic, string, logical//##||##gray|//none//##||##gray|//none//##||##gray|# do not return values:## _ += -= = /= @@//@@= %= @@*@@= _ += *= _ &= |= ^=|| || ||# null[#null-note null]||##gray|% Only used in place of numeric values:## _ NaN||NA NULL||None np.nan _ _ ##gray|# None cannot be stored in a numpy array; _
np.nan can if dtype is float64.##||##gray|# Only used in place of float values:## _
NaN|| ||# null-test[#null-test-note null test]||isnan(v) _ _ ##gray|% true for ‘‘, []:## _ isempty(v)||is.na(v) _ is.null(v)||v == None _ v is None _ _ np.isnan(np.nan) _ ##gray|# np.nan == np.nan is False##||isnan(v)|| ||# cond-expr[#cond-expr-note conditional expression]||##gray|//none//##||(if (x > 0) x else -x) _ ifelse(x > 0, x, -x)||x if x > 0 else -x||x > 0 ? x : -x|| ||||||||||~ # arithmetic-logic[#arithmetic-logic-note arithmetic and logic]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# boolean-type[#boolean-type-note boolean type]|| || ||##gray|# Python:## _ bool _ _ ##gray|# NumPy:## _ bool_||Bool|| ||# true-false[#true-false-note true and false] _ @< >@||1 0 true false||TRUE FALSE T F||True False||true false|| ||# falsehoods[#falsehoods-note falsehoods]||false 0 0.0 _ ##gray|//matrices evaluate to false unless nonempty and all entries evaluate to true//##||FALSE F 0 0.0 _ ##gray|//matrices evaluate to value of first entry; string in boolean context causes error//##||False None 0 0.0 ‘‘ [] {}||false|| ||# logical-op[#logical-op-note logical operators]||~true | (true & false) _ _ ##gray|% short-circuit operators:## _ && @@||@@||!TRUE | (TRUE & FALSE) _ ##gray|//short-circuit operators://## _ && @@||@@ _ _ ##gray|& //and// | //can operate on and return vectors, but// @@&&@@ //and// @@||@@ //return scalars//##||and or not||@@&& || !@@|| ||# relational-op[#relational-op-note relational operators] _ @< >@||== ~= > < >= <=||== != > < >= <=||== != > < >= <=||== != > < >= <=|| ||# int-type[#int-type-note integer type]|| || ||##gray|# Python:## _ int _ _ ##gray|# NumPy:## _ int8 int16 int32 int64||Int8 Int16 Int32 Int64 Int128 _ _ Int ##gray|//is either 32 or 64 bits, depending on//## WORD_SIZE|| ||# unsigned-type[#unsigned-type-note unsigned type]|| || ||uint8 uint16 uint32 uint64||UInt8 UInt16 UInt32 UInt64 UInt128 _ _ UInt ##gray|//is either 32 or 64 bits, depending on//## WORD_SIZE|| ||# float-type[#float-type-note float type] _ @< >@|| || ||##gray|# Python:## _ float _ _ ##gray|# NumPy:## _ float16 float32 float64||Float16 Float32 Float64|| ||# arith-op[#arith-op-note arithmetic operators] _ ##gray|//add, sub, mult, div, quot, rem//##||+ - * / ##gray|//none//## mod(##gray|//n//##, ##gray|//divisor//##)||+ - * / %/% %%||+ - * / // %||+ - * / div(##gray|//n//##, ##gray|//divisor//##) rem(##gray|//n//##, ##gray|//divisor//##) _ _ ##gray|# always non-negative:## _ mod(##gray|//n//##, ##gray|//divisor//##)|| ||# int-div[#int-div-note integer division] _ @< >@||fix(13 / 5)||13 %/% 5 _ as.integer(13 / 5)||13 // 5||div(13, 5)|| ||# int-div-zero[#int-div-zero-note integer division by zero] _ @< >@||Inf NaN ##gray|//or//## -Inf||##gray|//result of converting Inf or NaN to an integer with as.integer://## _ NA||##gray|//raises// ZeroDivisionError##||##gray|//raises// DivideError##|| ||# float-div[#float-div-note float division] _ @< >@||13 / 5||13 / 5||float(13) / 5||13 / 5 _ 5 \ 13|| ||# float-div-zero[#float-div-zero-note float division by zero] _ ##gray|//dividend is positive, zero, negative//##||##gray|//these values are literals://## _ Inf _ NaN _ -Inf||##gray|//these values are literals://## _ Inf _ NaN _ -Inf||##gray|//raises// ZeroDivisionError##||##gray|//these values are literals://## _ Inf _ NaN _ -Inf|| ||# power[#power-note power]||2 ^ 16||2 ^ 16 _ 2 ** 16||2 @@**@@ 16||2 ^ 16|| ||# sqrt[#sqrt-note sqrt] _ @< >@||sqrt(2)||sqrt(2)||math.sqrt(2)||sqrt(2)|| ||# sqrt-negative-one[#sqrt-negative-one-note sqrt -1]||##gray|% returns 0 + 1i:## _ sqrt(-1)||##gray|# returns NaN:## _ sqrt(-1) _ _ ##gray|# returns 0+1i:## _ sqrt(-1+0i)||##gray|# raises ValueError:## _ math.sqrt(-1) _ _ ##gray|# returns 1.41421j:## _ import cmath _ cmath.sqrt(-1)||##gray|# raises DomainError:## _ sqrt(-1) _ _ ##gray|# returns 0.0 + 1.0im:## _ sqrt(-1 + 0im)|| ||# transcendental-func[#transcendental-func-note transcendental functions]||exp log sin cos tan asin acos atan atan2||exp log sin cos tan asin acos atan atan2||math.exp math.log math.sin math.cos math.tan math.asin math.acos math.atan math.atan2||exp log sin cos tan asin acos atan atan2|| ||# transcendental-const[#transcendental-const-note transcendental constants]||pi e||pi exp(1)||math.pi math.e||pi e|| ||# float-truncation[#float-truncation-note float truncation] _ ##gray|//round towards zero, to nearest integer, down, up//##||fix(x) _ round(x) _ floor(x) _ ceil(x)||as.integer(x) _ round(x) _ floor(x) _ ceiling(x)||int(x) _ int(round(x)) _ math.floor(x) _ math.ceil(x)||Int(trunc(x)) _ Int(round(x)) _ Int(floor(x)) _ Int(ceil(x)) _ _ ##gray|# trunc() and other functions return floats. _
Int() raises InexactError if float argument has _
nonzero fractional portion.##||
||# absolute-val[#absolute-val-note absolute value] _ ##gray|//and signum//##||abs sign||abs sign||abs(-3.7) _ math.copysign(1, -3.7)||abs(-3.7) _ sign(-3.7)|| ||# int-overflow[#int-overflow-note integer overflow]||##gray|//becomes float; largest representable integer in the variable// intmax##||##gray|//becomes float; largest representable integer in the variable// .Machine$integer.max##||##gray|//becomes arbitrary length integer of type// long##|| || ||# float-overflow[#float-overflow-note float overflow] _ @< >@||Inf||Inf||##gray|//raises// OverflowError##|| || ||# float-limits[#float-limits-note float limits] _ @< >@||eps _ realmax _ realmin||.Machine$double.eps _ .Machine$double.xmax _ .Machine$double.xmin||np.finfo(np.float64).eps _ np.finfo(np.float64).max _ np.finfo(np.float64).min|| || ||# rational-construction[#rational-construction-note rational construction]|| || || ||22 @@//@@ 7|| ||# rational-decomposition[#rational-decomposition-note rational decomposition]|| || || ||num(22 @@//@@ 7) _ den(22 @@//@@ 7)|| ||# complex-types[#complex-types-note complex types]|| || ||complex64 complex128||Complex32 Complex64 Complex128|| ||# complex-construction[#complex-construction-note complex construction] _ @< >@||1 + 3i||1 + 3i||1 + 3j||1 + 3im _ complex(1, 3)|| ||# complex-decomposition[#complex-decomposition-note complex decomposition]||real imag _ abs arg _ conj||Re Im _ abs Arg _ Conj||import cmath _ _ z.real _ z.imag _ cmath.polar(z)[1]||real(1 + 3im) _ imag(1 + 3im) _ abs(1 + 3im) _ angle(1 + 3im) _ conj(1 + 3im)|| ||# random-num[#random-num-note random number] _ ##gray|//uniform integer, uniform float//##||floor(100 * rand) _ rand||floor(100 * runif(1)) _ runif(1)||np.random.randint(0, 100) _ np.random.rand()||rand(1:100) _ rand()|| ||# random-seed[#random-seed-note random seed] _ ##gray|//set, get, and restore//##||rand(‘state’, 17) _ sd = rand(‘state’) _ rand(‘state’, sd)||set.seed(17) _ sd = .Random.seed _ ##gray|//none//##||np.random.seed(17) _ sd = np.random.get_state() _ np.random.set_state(sd)|| || ||# bit-op[#bit-op-note bit operators]||bitshift(100, 3) _ bitshift(100, -3) _ bitand(1, 2) _ bitor(1, 2) _ bitxor(1, 2) _ ##gray|% MATLAB:## _ bitcmp(1, ‘uint16’) _ ##gray|% Octave:## _ bitcmp(1, 16)||##gray|//none//##||100 @@<<@@ 3 _ 100 @@>>@@ 3 _ 1 & 2 _ 1 | 2 _ 1 ^ 2 _ ~1|| || ||# binary-octal-hex-literals[#binary-octal-hex-literals-note binary, octal, and hex literals]|| || || ||0b101010 _ 0o52 _ 0x2a|| ||# radix[#radix-note radix] _ ##gray|//convert integer to and from string with radix//##|| || || ||base(7, 42) _ parse(Int, “60”, 7)|| ||||||||||~ # strings[#strings-note strings]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# str-literal[#str-literal-note literal]|| ‘don’’t say “no”’ _ _ ##gray|% Octave only:## _ “don’t say "no"”||"don’t say "no"” _ ‘don\’t say “no”’||’don\’t say “no”’ _ “don’t say "no"” _ r"don’t “ r’say “no”’||"don’t say "no"”|| ||# str-newline[#str-newline-note newline in literal] _ @< >@||##gray|//no//##||##gray|//yes//##||##gray|//no//##||##gray|//yes//##|| ||# str-esc[#str-esc-note literal escapes]||##gray|% Octave double quote only:## _ \ " \’ \0 \a \b \f \n \r \t \v||\ " \’ \a \b \f \n \r \t \v ##gray|//ooo//##||##gray|# single and double quoted:## _ ##gray|//newline//## \ \’ " \a \b \f \n \r \t \v ##gray|//ooo//## \x##gray|//hh//##||\ " \’ \a \b \f \n \t \r \v _ ##gray|//ooo//## \x##gray|//hh//## \u##gray|//hhhh//## \U##gray|//hhhhhhhh//##|| ||# var-interpolation[#var-interpolation-note variable interpolation]|| || || ||count = 3 _ item = “ball” _ println(“$count $(item)s”)|| ||# expr-interpolation[#expr-interpolation-note expression interpolation] _ @< >@|| || || ||"1 + 1 = $(1 + 1)”|| ||# str-concat[#str-concat-note concatenate]||strcat(‘one ‘, ‘two ‘, ‘three’)||paste(“one”, “two”, “three”, sep=” “)||’one ‘ + ‘two ‘ + ‘three’ _ ##gray|//literals, but not variables, can be concatenated with juxtaposition://## _ ‘one ‘ “two “ ‘three’||"one “ * “two “ * “three” _ _ string(“one “, “two “, “three”)|| ||# str-replicate[#str-replicate-note replicate] _ @< >@||hbar = repmat(‘-’, 1, 80)||hbar = paste(rep(‘-’, 80), collapse=’’)||hbar = ‘-’ * 80||hbar = “-” ^ 80 _ _ hbar = repeat(“-”, 80)|| ||# index-substr[#index-substr-note index of substring]||##gray|% returns array of one-indexed _ % locations ## _ strfind(‘hello’, ‘el’)||##gray|//counts from one, returns _ -1 if not found//## _ regexpr(“el”, “hello”)||##gray|# Counts from zero; raises ValueError if not found:## _ ‘hello’.index(‘el’)||##gray|# returns UnitRange:## _ search(“hello”, “el”)|| ||# extract-substr[#extract-substr-note extract substring] _ @< >@||s = ‘hello’ _ ##gray|% syntax error: ‘hello’(1:4)## _ s(1:4)||substr(“hello”, 1, 4)||’hello’[0:4]||"hello”[1:4]|| ||# split[#split-note split]|| ##gray|% returns cell array:## _ strsplit(‘foo,bar,baz’, ‘,’)||strsplit(‘foo,bar,baz’, ‘,’)||’foo,bar,baz’.split(‘,’)||split(“foo,bar,baz”, “,”)|| ||# join[#join-note join]||##gray|% takes cell array as arg:## _ strjoin({’foo’, ‘bar’, ‘baz’}, ‘,’)||paste(“foo”, “bar”, “baz”, sep=”,”) _ paste(c(‘foo’, ‘bar’, ‘baz’), _ @< >@collapse=’,’)||’,’.join([‘foo’, ‘bar’, ‘baz’])||join([“foo”, “bar”, “baz”], “,”)|| ||# trim[#trim-note trim] _ ##gray|//both sides, left, right//##||strtrim(‘ foo ‘) _ ##gray|//none//## _ deblank(‘foo ‘)||gsub(“(^[\n\t ]+|[\n\t ]+$)”, _ @< >@””, _ @< >@” foo “) _ sub(“^[\n\t ]+”, ““, “ foo”) _ sub(“[\n\t ]+$”, ““, “foo “)||’ foo ‘.strip() _ ‘ foo’.lstrip() _ ‘foo ‘.rstrip()|| || ||# pad[#pad-note pad] _ ##gray|//on right, on left, centered//##||s = repmat(‘ ‘, 1, 10) _ s(1:5) = ‘lorem’ _ strjust(s, ‘left’) _ strjust(s, ‘right’) _ strjust(s, ‘center’)||sprintf(“%-10s”, “lorem”) _ sprintf(“%10s”, “lorem”) _ ##gray|//none//##||’lorem’.ljust(10) _ ‘lorem’.rjust(10) _ ‘lorem’.center(10)|| || ||# num-to-str[#num-to-str-note number to string] _ @< >@||strcat(‘value: ‘, num2str(8))||paste(“value: “, toString(“8”))||’value: ‘ + str(8)|| || ||# str-to-num[#str-to-num-note string to number]||7 + str2num(‘12’) _ 73.9 + str2num(‘.037’)||7 + as.integer(“12”) _ 73.9 + as.double(“.037”)||7 + int(‘12’) _ 73.9 + float(‘.037’)||7 + parse(Int, “12”) _ 73.9 + parse(Float64, “.037”)|| ||# case-manipulation[#case-manipulation-note translate case]||lower(‘FOO’) _ upper(‘foo’)||tolower(“FOO”) _ toupper(“foo”)||’foo’.upper() _ ‘FOO’.lower()||uppercase(“foo”) _ lowercase(“FOO”)|| ||# sprintf[#sprintf-note sprintf] _ @< >@||sprintf(‘%s: %.3f %d’, ‘foo’, 2.2, 7)||sprintf(“%s: %.3f %d”, “foo”, 2.2, 7)||’%s: %.3f %d’ % (‘foo’, 2.2, 7)||@sprintf(“%s: %.2f %d”, “foo”, 2.2, 7)|| ||# str-len[#str-len-note length] _ @< >@||length(‘hello’)||nchar(“hello”)||len(‘hello’)||length(“hello”) _ _ ##gray|# index of first byte of last char:## _ endof(“hello”)|| ||# char-access[#char-access-note character access] _ @< >@||s = ‘hello’ _ ##gray|% syntax error: ‘hello’(1)## _ s(1)||substr(“hello”, 1, 1)||’hello’[0]||"hello”[1] _ _ ##gray|# index must be byte-index of the first byte of a _
character. Raises BoundsErrror if no such byte, _
and UnicodeError if byte not first in char.##||
||# chr-ord[#chr-ord-note chr and ord]||char(65) _ double(‘A’)||intToUtf8(65) _ utf8ToInt(“A”)||chr(65) _ ord(‘A’)||Char(65) _ Int(‘A’)|| ||||||||||~ # regexes[#regexes-note regular expressions]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# char-class-abbrevs[#char-class-abbrevs-note character class abbreviations]||. \d \D \s \S \w \W _ _ ##gray|% also C-string style backslash escapes:## _ \a \b \f \n \r \t \v||##gray|# escape backslash in strings by doubling:## _ . \d \D \s \S \w \W||. \d \D \s \S \w \W||. \d \D \h \H \s \S \v \V \w \W|| ||# regex-anchors[#regex-anchors-note anchors] _ @< >@||^ $ < >||##gray|# escape backslash in strings by doubling:## _ ^ $ < > \b \B||^ $ \A \b \B \Z||^ $ \A \b \B \z \Z|| ||# regex-match[#regex-match-note match test]||regexp(‘hello’, ‘^[a-z]+$’) _ regexp(‘hello’, ‘\S+$’)||regexpr(“[a-z]+$”, “hello”) > 0 _ regexpr(‘^\S+$’, “hello”) > 0||re.search(r’^[a-z]+$’, ‘hello’) _ re.search(r’^\S+$’, ‘hello’)||ismatch(r”^[a-z]+$”, “hello”)|| ||# case-insensitive-regex-match[#case-insensitive-regex-match-note case insensitive match test]||regexpi(‘Lorem Ipsum’, ‘lorem’)||regexpr(‘(?i)lorem’, “Lorem Ipsum”) > 0||re.search(r’lorem’, ‘Lorem Ipsum’, re.I)||ismatch(r"lorem"i, “Lorem Ipsum”)|| ||# regex-modifiers[#regex-modifiers-note modifiers] _ @< >@||##gray|//none//##||(?i) (?m) (?s) (?x)||re.I re.M re.S re.X||i m s x|| ||# regex-subst[#regex-subst-note substitution] _ ##gray|//first match, all matches//##||s = ‘do re mi mi mi’ _ regexprep(s, ‘ma’, ‘once’) _ regexprep(s, ‘mi’, ‘ma’)||sub(‘mi’, ‘ma’, ‘do re mi mi mi’) _ gsub(‘mi’, ‘ma’, ‘do re mi mi mi’)||rx = re.compile(r’mi’) _ s = rx.sub(‘ma’, ‘do re mi mi mi’, 1) _ s2 = rx.sub(‘ma’, ‘do re mi mi mi’)||replace(“do re mi mi mi”, r"mi”, s"ma”, 1) _ replace(“do re mi mi mi”, r"mi”, s"ma”)|| ||# regex-backreference[#regex-backreference-note backreference in match and substitution]||regexp(‘do do’, ‘(\w+) \1’) _ regexprep(‘do re’, ‘(\w+) (\w+)’, ‘$2 $1’)||regexpr(‘(\w+) \1’, ‘do do’) > 0 _ sub(‘(\w+) (\w+)’, ‘\2 \1’, ‘do re’)||##gray|//none//## _ _ rx = re.compile(r’(\w+) (\w+)’) _ rx.sub(r’\2 \1’, ‘do re’)||ismatch(r”(\w+) \1”, “do do”)|| ||# group-capture[#group-capture-note group capture]|| || ||rx = ‘(\d{4})-(\d{2})-(\d{2})’ _ m = re.search(rx, ‘2010-06-03’) _ yr, mo, dy = m.groups()||rx = r”(\d{4})-(\d{2})-(\d{2})” _ m = match(rx, “2010-06-03”) _ yr, mn, dy = m.captures|| ||||||||||~ # dates-time[#dates-time-note dates and time]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# current-date-time[#current-date-time-note current date/time] _ @< >@||t = now||t = as.POSIXlt(Sys.time())||import datetime _ _ t = datetime.datetime.now()||t = now()|| ||# date-time-type[#date-time-type-note date/time type]||##gray|//floating point number representing days since year 0 in the Gregorian calendar//##||POSIXlt||datettime||DateTime|| ||# date-time-diff-type[#date-time-diff-type-note date/time difference type]||##gray|//floating point number representing days//##||##gray|//a// difftime //object which behaves like a floating point number representing seconds//##||##gray|timedelta, //which can be converted to float value in seconds via// total_seconds() //method//##||Base.Dates.Millisecond|| ||# date-parts[#date-parts-note get date parts]||dv = datevec(t) _ dv(1) _ dv(2) _ dv(3) _ ##gray|% syntax error: datevec(t)(1)##||t$year + 1900 _ t$mon + 1 _ t$mday||t.year _ t.month _ t.day||Dates.year(t) _ Dates.month(t) _ Dates.day(t)|| ||# time-parts[#time-parts-note get time parts]||dv = datevec(t) _ dv(4) _ dv(5) _ dv(6)||t$hour _ t$min _ t$sec||t.hour _ t.minute _ t.second||Dates.hour(t) _ Dates.minute(t) _ Dates.second(t)|| ||# build-date-time[#build-date-time-note build date/time from parts]||t = datenum([2011 9 20 23 1 2])||t = as.POSIXlt(Sys.time()) _ t$year = 2011 - 1900 _ t$mon = 9 - 1 _ t$mday = 20 _ t$hour = 23 _ t$min = 1 _ t$sec = 2||import datetime _ _ t = datetime.datetime(2011, 9, 20, 23, 1, 2)||t = DateTime(2011, 9, 20, 23, 1, 2)|| ||# date-to-str[#date-to-str-note convert to string] _ @< >@||datestr(t)||print(t)||str(t)||”$t”|| ||# strptime[#strptime-note parse datetime]||s = ‘2011-09-20 23:01:02’ _ fmt = ‘yyyy-mm-dd HH:MM:SS’ _ t = datenum(s, fmt)||t = strptime(‘2011-09-20 23:01:02’, _ @< >@’%Y-%m-%d %H:%M:%S’)||import datetime _ _ s = ‘2011-05-03 10:00:00’ _ fmt = ‘%Y-%m-%d %H:%M:%S’ _ t = datetime.datetime.strptime(s, fmt)||fmt = “yyyy-mm-dd HH:MM:SS” _ t = DateTime(“2011-05-03 10:00:00”, fmt) _ _ ##gray|# fmt string can be compiled:## _ df = Dates.DateFormat(fmt) _ t2 = DateTime(“2011-05-03 10:00:00”, df)|| ||# strftime[#strftime-note format datetime] _ @< >@||datestr(t, ‘yyyy-mm-dd HH:MM:SS’)||format(t, format=’%Y-%m-%d %H:%M:%S’)||t.strftime(‘%Y-%m-%d %H:%M:%S’)||Dates.format(t, “yyyy-mm-dd HH:MM:SS”)|| ||# sleep[#sleep-note sleep]||pause(0.5)||Sys.sleep(0.5)||import time _ _ time.sleep(0.5)||sleep(0.5)|| ||||||||||~ # tuples[#tuples-note tuples]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# tuple-type[#tuple-type-note type] _ @< >@||cell||list||tuple||Tuple{##gray|T[, @@…@@]##}|| ||# tuple-literal[#tuple-literal-note literal] _ @< >@||tup = {1.7, ‘hello’, [1 2 3]}||tup = list(1.7, “hello”, c(1, 2, 3))||tup = (1.7, “hello”, [1,2,3])||tup = (1.7, “foo”, [1, 2, 3])|| ||# tuple-access[#tuple-access-note lookup element] _ @< >@||##gray|% indices start at one:## _ tup{1}||##gray|# indices start at one:## _ tup1||##gray|# indices start at zero:## _ tup[0]||##gray|# indices start at one:## _ tup[1]|| ||# tuple-update[#tuple-update-note update element] _ @< >@||tup{1} = 2.7||tup1 = 2.7||##gray|//tuples are immutable//##||##gray|//tuples are immutable//##|| ||# tuple-len[#tuple-len-note length] _ @< >@||length(tup)||length(tup)||len(tup)||length(tup)|| ||||||||||~ # arrays[#arrays-note arrays]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# array-elem-type[#array-elem-type-note element type]||##gray|//always numeric//##||##gray|# “numeric”:## _ class(c(1, 2, 3)) _ _ ##gray|# arrays can also have “boolean” or “string” elements##||##gray|# values can have different types:## _ [type(x) for x in a]||a = [1, 2, 3] _ _ ##gray|# Array{Int64, 2}:## _ typeof(a) _ ##gray|# Int64:## _ typeof(a[1])|| ||# array-literal[#array-literal-note literal] _ @< >@||a = [1, 2, 3, 4] _ _ ##gray|% commas are optional:## _ a = [1 2 3 4]||##gray|# use c() constructor:## _ a = c(1, 2, 3, 4)||a = [1, 2, 3, 4]||a = [1, 2, 3, 4]|| ||# array-size[#array-size-note size] _ @< >@||length(a)||length(a)||len(a)||length(a)|| ||# array-empty-test[#array-empty-test-note empty test] _ @< >@||length(a) == 0 _ _ ##gray|% An array used in a conditional test is _ % false unless nonempty and all entries evaluate _ % as true.##||length(a) == 0||not a||isempty(a)|| ||# array-lookup[#array-lookup-note lookup] _ @< >@||##gray|% Indices start at one:## _ a(1)||##gray|# Indices start at one:## _ a[1]||##gray|# Indices start at zero:## _ a[0]||##gray|# Indices start at one:## _ a[1]|| ||# array-update[#array-update-note update] _ @< >@||a(1) = -1||a[1] = -1||a[0] = -1||a[1] = -1|| ||# array-out-of-bounds[#array-out-of-bounds-note out-of-bounds behavior]||a = [] _ _ ##gray|% error:## _ a(1) _ _ ##gray|% increases array size to 10; _ % zero-fills slots 1 through 9:## _ a(10) = 10||a = c() _ ##gray|# evaluates as NA:## _ a[10] _ ##gray|# increases array size to 10:## _ a[10] = “lorem”||a = [] _ ##gray|# raises IndexError:## _ a[10] _ ##gray|# raises IndexError:## _ a[10] = ‘lorem’||a = [] _ _ ##gray|# raises BoundsError:## _ a[10] _ ##gray|# raises BoundsError:## _ a[10] = “lorem”|| ||# array-element-index[#array-element-index-note index of element]||a = [7 8 9 10 8] _ _ ##gray|% returns [2 5]:## _ find(a == 8) _ _ ##gray|% returns 2:## _ find(a == 8, 1, ‘first’)||a = c(‘x’, ‘y’, ‘z’, ‘w’, ‘y’) _ _ ##gray|# c(2, 5):## _ which(a == ‘y’)||a = [‘x’, ‘y’, ‘z’, ‘w’, ‘y’] _ _ a.index(‘y’)@< >@##gray|# 1## _ a.rindex(‘y’)@< >@##gray|# 4##||a = [“x”, “y”, “z”, “w”, “y”] _ _ ##gray|# 2:## _ findfirst(a, “y”) _ ##gray|# 5:## _ julia> findlast(a, “y”)|| ||# array-slice[#array-slice-note slice] _ ##gray|//by endpoints//##||a = [‘a’ ‘b’ ‘c’ ‘d’ ‘e’] _ _ ##gray|% [‘c’ ‘d’]:## _ a(3:4)||a = c(“a”, “b”, “c”, “d”, “e”) _ _ ##gray|# c(“c”, “d”):## _ a[seq(3, 4)]||a = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] _ _ ##gray|# [‘c’, ‘d’]:## _ a[2:4]||a = [“a”, “b”, “c”, “d”, “e”] _ _ ##gray|# [“c”, “d”]:## _ a[3:4]|| ||# array-slice-to-end[#array-slice-to-end-note slice to end] _ @< >@||a = [‘a’ ‘b’ ‘c’ ‘d’ ‘e’] _ _ ##gray|% [‘c’ ‘d’ ‘e’]:## _ a(3:end)||a = c(“a”, “b”, “c”, “d”, “e”) _ _ ##gray|# both return c(“c”, “d”, “e”):## _ tail(a, n=length(a) - 2) _ a[-1:-2]||a = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’] _ _ ##gray|# [‘c’, ‘d’, ‘e’]:## _ a[2:]||a = [“a”, “b”, “c”, “d”, “e”] _ _ ##gray|# [“c”, “d”, “e”]:## _ a[3:end]|| ||# int-array-as-index[#int-array-as-index integer array as index]||7 8 9||c(7, 8, 9)[c(1, 3, 3)]||np.array([7, 8, 9])0, 2, 2||##gray|# [7, 9, 9]:## _ [7, 8, 9]1, 3, 3|| ||# logical-array-as-index[#logical-array-as-index logical array as index]||7 8 9||c(7, 8, 9)[c(T, F, T)]||np.array([7, 8, 9])True, False, True||##gray|# [7, 9]:## _ [7, 8, 9]true, false, true|| ||# array-concatenation[#array-concatenation-note concatenate]||a = [1 2 3] _ a2 = [a [4 5 6]] _ a = [a [4 5 6]] _ ##gray|% or:## _ a = horzcat(a, a2)||a = c(1, 2, 3) _ a2 = append(a, c(4, 5, 6)) _ a = append(a, c(4, 5, 6))||a = [1, 2, 3] _ a2 = a + [4, 5, 6] _ a.extend([4, 5, 6])||a = [1, 2, 3] _ a2 = vcat(a, [4, 5, 6]) _ a = vcat(a, [4, 5, 6])|| ||# array-replication[#array-replication-note replicate]||a = repmat(NA, 1, 10)||a = rep(NA, 10) _ _ ##gray|# 30 a’s, 50 b’s, and 90 c’s:## _ rep(c(“a”, “b”, “c”), c(30, 50, 90))||a = [None] * 10 _ a = [None for i in range(0, 10)]||fill(NaN, 10)|| ||# array-copy[#array-copy-note copy] _ ##gray|//address copy, shallow copy, deep copy//##||##gray|//There is no address copy. Because arrays cannot be nested, there is no distinction between shallow copy and deep copy. Assignment and passing an array to a function can be regarded as performing a shallow or deep copy, though MATLAB does not allocate memory for a 2nd array until one of the arrays is modified.//##||##gray|//Arrays in R behave like arrays in MATLAB.//##||import copy _ _ a = [1, 2, [3, 4]] _ _ a2 = a _ a3 = list(a) _ a4 = copy.deepcopy(a)||a = Any[1, 2, [3, 4]] _ _ a2 = a _ a3 = copy(a) _ a4 = deepcopy(a)|| ||# array-iteration[#array-iteration-note iteration] _ @< >@||a = [9 7 3] _ for i = 1:numel(a) _ @< >@x = a(i) _ @< >@disp(x) _ end||for (x in c(9, 7, 3)) { _ @< >@print(x) _ }||for i in [9, 7, 3]: _ @< >@print(i)||for i = [9, 7, 3] _ @< >@println(i) _ end|| ||# indexed-array-iteration[#indexed-array-iteration-note indexed iteration]|| ||for (i in seq_along(a)) { _ @< >@cat(sprintf(“%s at index %d\n”, i, a[i])) _ }||a = [‘do’, ‘re’, ‘mi’, ‘fa’] _ for i, s in enumerate(a): _ @< >@print(‘%s at index %d’ % (s, i))||a = [“do”, “re”, “mi”, “fa”] _ for (i, s) in enumerate(a) _ @< >@println(i, “ “, s) _ end|| ||# array-reverse[#array-reverse-note reverse]||a = [1 2 3] _ a2 = fliplr(a) _ a = fliplr(a)||a = c(1, 2, 3) _ a2 = rev(a) _ a = rev(a)||a = [1, 2, 3] _ a2 = a[::-1] _ a.reverse()||a = [1, 2, 3] _ a2 = reverse(a) _ reverse!(a)|| ||# array-sort[#array-sort-note sort]||a = [3 1 4 2] _ a = sort(a)||a = c(‘b’, ‘A’, ‘a’, ‘B’) _ a2 = sort(a) _ a = sort(a)||a = [‘b’, ‘A’, ‘a’, ‘B’] _ sorted(a) _ a.sort() _ a.sort(key=str.lower)||a = [3, 1, 4, 2] _ a2 = sort(a) _ sort!(a)|| ||# array-dedupe[#array-dedupe-note dedupe]||a = [1 2 2 3] _ a2 = unique(a)||a = c(1, 2, 2, 3) _ a2 = unique(a)||a = [1, 2, 2, 3] _ a2 = list(set(a)))||a = unique([1, 2, 2, 3])|| ||# membership[#membership-note membership] _ @< >@||ismember(7, a)||7 %in% a _ is.element(7, a)||7 in a||7 in a _ 7 ∈ a _ a ∋ 7|| ||# intersection[#intersection-note intersection] _ @< >@||intersect([1 2], [2 3 4])||intersect(c(1, 2), c(2, 3, 4))||{1, 2} & {2, 3, 4}||intersection([1, 2], [2, 3, 4]) _ ∩([1, 2], [2, 3, 4])|| ||# union[#union-note union] _ @< >@||union([1 2], [2 3 4])||union(c(1, 2), c(2, 3, 4))||{1, 2} | {2, 3, 4}||union([1, 2], [2, 3, 4]) _ ∪([1, 2], [2, 3, 4])||| ||# set-diff[#set-diff-note relative complement, symmetric difference]||setdiff([1 2 3], [2]) _ _ a1 = [1 2] _ a2 = [2 3 4] _ union(setdiff(a1, a2), setdiff(a2, a1))||setdiff(c(1, 2, 3), c(2)) _ _ union(setdiff(c(1, 2), c(2, 3, 4)), _ @< >@setdiff(c(2, 3, 4), c(1, 2)))||{1, 2, 3} - {2} _ _ {1, 2} ^ {2, 3, 4}||setdiff([1, 2, 3], [2]) _ symdiff([1, 2], [2, 3, 4])|| ||# map[#map-note map] _ @< >@||arrayfun( @(x) x*x, [1 2 3])||sapply(c(1,2,3), function (x) { x * x})||map(lambda x: x * x, [1, 2, 3]) _ ##gray|# or use list comprehension:## _ [x * x for x in [1, 2, 3]]|| || ||# filter[#filter-note filter] _ @< >@||a = [1 2 3] _ a(a > 2)||a = c(1, 2, 3) _ a[a > 2] _ _ Filter(function(x) { x > 2}, a)||filter(lambda x: x > 1, [1, 2, 3]) _ ##gray|# or use list comprehension:## _ [x for x in [1, 2, 3] if x > 1]|| || ||# reduce[#reduce-note reduce] _ @< >@|| ||Reduce(function(x, y) { x + y }, c(1, 2, 3), 0)||reduce(lambda x, y: x + y, [1 ,2, 3], 0)||reduce(+, [1, 2, 3]) _ foldl(-, 0, [1, 2, 3]) _ foldr(-, 0, [1, 2, 3])|| ||# universal-existential-test[#universal-existential-test-note universal and existential tests] _ @< >@||all(mod([1 2 3 4], 2) == 0) _ any(mod([1 2 3 4]) == 0)||all(c(1, 2, 3, 4) %% 2 == 0) _ any(c(1, 2, 3, 4) %% 2 == 0)||all(i % 2 == 0 for i in [1, 2, 3, 4]) _ any(i % 2 == 0 for i in [1, 2, 3, 4])||all([x % 2 == 0 for x in [1, 2, 3, 4]]) _ any([x % 2 == 0 for x in [1, 2, 3, 4]])|| ||# shuffle-sample[#shuffle-sample-note shuffle and sample]|| ||a = c(1, 1, 2, 3, 9, 28) _ sample(a, 3) _ a[sample.int(length(a))]||from random import shuffle, sample _ _ a = [1, 2, 3, 4] _ shuffle(a) _ sample(a, 2)|| || ||# zip[#zip-note zip] _ @< >@||##gray|//none; MATLAB arrays can’t be nested//##||##gray|# R arrays can’t be nested. _
One approximation of zip is a 2d array:## _
a = rbind(c(1, 2, 3), c(‘a’, ‘b’, ‘c’)) _ _ ##gray|# To prevent data type coercion, use a data frame:## _ df = data.frame(numbers=c(1, 2, 3), _ @< >@letters=c(‘a’, ‘b’, ‘c’))||##gray|# array of 3 pairs:## _ a = zip([1, 2, 3], [‘a’, ‘b’, ‘c’])|| || ||||||||||~ # arithmetic-sequences[#arithmetic-sequences-note arithmetic sequences]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# arith-seq-diff-one[#arith-seq-diff-one-note unit difference]||1:100||##gray|# type integer:## _ 1:100 _ seq(1, 100) _ _ ##gray|# type double:## _ seq(1, 100, 1)||range(1, 101)||1:100|| ||# arith-seq-diff-ten[#arith-seq-diff-ten-note difference of 10]||0:10:100||##gray|# type double:## _ seq(0, 100, 10)||range(0, 101, 10)||0:10:100|| ||# arith-seq-diff-tenth[#arith-seq-diff-tenth-note difference of 0.1]||0:0.1:10||seq(0, 10, 0.1)||[0.1 * x for x in range(0, 101)] _ _ ##gray|# 3rd arg is length of sequence, not step size:## _ sp.linspace(0, 10, 100)||0:0.1:10|| ||# arith-seq-computed-diff[#arith-seq-computed-diff-note computed difference]||##gray|% 100 evenly spaced values:## _ linspace(3.7, 19.4, 100) _ _ ##gray|% 100 is default num. of elements:## _ linspace(3.7, 19.4)|| ||numpy.linspace(3.7, 19.4, 100) || || ||# iter-over-arith-seq[#iter-over-arith-seq-note iterate]|| || ||##gray|# range replaces xrange in Python 3:## _ n = 0; _ for i in xrange(1, 1000001): _ @< >@n += i||n = 0 _ for i in 1:1000000 _ @< >@n += i _ end|| ||# arith-seq-to-array[#arith-seq-to-array-note to array]|| || ||a = range(1, 11) _ ##gray|# Python 3:## _ a = list(range(1, 11))||a = Array(1:10)|| ||||||||||~ # two-d-arrays[#two-d-arrays-note two dimensional arrays]|| ||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]|| ||# array-2d-elem-type[#array-2d-elem-type-note element type]||##gray|//always numeric//##||A = array(c(1, 2, 3, 4), dim=c(2, 2)) _ _ ##gray|# “array”:## _ class(A) _ _ ##gray|# “boolean”, “numeric”, or “string”:## _ class(c(A))||np.array([[1, 2], [3, 4]]).dtype _ _ ##gray|# possible values: np.bool, np.int64, _
np.float64, np.complex128, @@…@@##||A = [1 2; 3 4] _
_ eltype(A)|| ||# array-2d-literal[#array-2d-literal-note literal]||[1, 2; 3, 4] _ _ ##gray|% commas optional; newlines can replace semicolons::## _ [1 2 _ @< >@3 4]||##gray|//none//##||##gray|//none//##||[1 2; 3 4] _ _ ##gray|# A 1-d array created with commas is a _
n×1 array. If commas are used in a literal, _
then semicolons and spaces as delimiters.## _
_ [1 2 _ @< >@3 4]|| ||# array-2d-construct-seq[#array-2d-construct-seq-note construct from sequence]||reshape([1 2 3 4], 2, 2)||array(c(1, 2, 3, 4), dim=c(2, 2))||A = np.array([1, 2, 3, 4]).reshape(2, 2) _ _ ##gray|# convert to nested Python lists:## _ A.tolist()||reshape([1, 2, 3, 4], 2, 2)|| ||# array-2d-construct-rows[#array-2d-construct-rows-note construct from rows]||row1 = [1 2 3] _ row2 = [4 5 6] _ _ A = [row1; row2]||rbind(c(1, 2, 3), c(4, 5, 6))||row1 = np.array([1, 2, 3]) _ row2 = np.array([4, 5, 6]) _ _ np.vstack((row1, row2)) _ _ np.array([[1, 2], [3, 4]])||vcat([1 2 3], [4 5 6]) _ _ row1 = [1 2 3] _ row2 = [4 5 6] _ [row1; row2]|| ||# array-2d-construct-columns[#array-2d-construct-columns-note construct from columns]||col1 = [1; 4] _ col2 = [2; 5] _ col3 = [3; 6] _ _ ##gray|% commas are optional:## _ A = [col1, col2, col3]||cbind(c(1, 4), c(2, 5), c(3, 6))||cols = ( _ @< >@np.array([1, 4]), _ @< >@np.array([2, 5]), _ @< >@np.array([3, 6]) _ ) _ np.vstack(cols).transpose()||hcat([1, 4], [2, 5], [3, 6]) _ _ col1 = [1, 4] _ col2 = [2, 5] _ col3 = [3, 6] _ [col1 col2 col3]|| ||# array-2d-construct-subarrays[#array-2d-construct-subarrays-note construct from subarrays]||A = [1 3; 2 4] _ _ A4by2 = [A; A] _ A2by4 = [A A]||A = matrix(c(1, 2, 3, 4), nrow=2) _ A4by2 = rbind(A, A) _ A2by4 = cbind(A, A)||A = np.array([[1, 2], [3, 4]]) _ A2by4 = np.hstack([A, A]) _ A4by2 = np.vstack([A, A])||A = [1 2; 3 4] _ A4by2 = [A; A] _ A2by4 = [A A ]|| ||# array-2d-cast[#array-2d-cast-note cast element type]|| || || || || ||# array-2d-size[#array-2d-size-note size] _ ##gray|//number of elements, number of dimensions, dimension lengths//##||numel(A) _ ndims(A) _ size(A) _ _
gray|% length of 1st dimension (i.e. # of rows):## _
size(A, 1) _
_
##gray|% length of longest dimension:## _
length(A)||length(A) _
length(dim(A)) _
dim(A)||A.size _
A.ndim _
A.shape _
_
##gray|# number of rows:## _
len(A)||length(A) _
ndims(A) _
size(A)||
||# array-2d-lookup[#array-2d-lookup-note lookup]||##gray|% indices start at one:## _
1 2; 3 4||##gray|# indices start at one:## _
A = array(c(1, 2, 3, 4), dim=c(2, 2) _
_
A[1, 1]||##gray|# indices start at zero:## _
A = np.array([[1, 2], [3, 4]]) _
_
A[0][0] ##gray|//or//## _
A[0, 0]||##gray|# indices start at one:## _
A[1, 1]||
||# array-2d-1d-lookup[#array-2d-1d-lookup-note 1d lookup]||A = [2 4; 6 8] _
##gray|% returns 8:## _
A(4) _
_
##gray|% convert to column vector of length 4:## _
A2 = A(:)||A = array(c(2, 4, 6, 8), dim=c(2, 2)) _
_
##gray|# returns 8:## _
A[4]||A = np.array([[2, 4], [6, 8]]) _
_
##gray|# returns np.array([6, 8]):## _
A[1] _
_
##gray|# returns 8:## _
A.flat[3]||A = [2 4; 6 8] _
_
##gray|# returns 8:## _
A[4]||
||# array-2d-slice[#array-2d-slice-note lookup row or column]||A = [1 2 3; 4 5 6; 7 8 9] _
_
##gray|% 2nd row:## _
A(2, :) _
_
##gray|% 2nd column:## _
A(:, 2)||A = t(array(1:9, dim=c(3, 3))) _
_
##gray|# 2nd row:## _
A[2, ] _
_
##gray|# 2nd column:## _
A[, 2]||A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) _
_
##gray|# 2nd row:## _
A[1, :] _
_
##gray|# 2nd column:## _
A[:, 1]|| A = [1 2 3; 4 5 6; 7 8 9] _
_
##gray|# 2nd row:## _
A[2, :] _
_
##gray|# 2nd column:## _
A[:, 2]||
||# array-2d-update[#array-2d-update-note update]||A = [2 4; 6 8] _
A(1, 1) = 3||A = array(c(2, 4, 6, 8), dim=c(2, 2)) _
A[1, 1] = 3||A = np.array([[2, 4], [6, 8]]) _
A[0, 0] = 3||A = [2 4; 6 8] _
A[1, 1] = 3||
||# array-2d-update-row-col[#array-2d-update-row-col-note update row or column]||A = [1 2; 3 4] _
_
##gray|% [2 1; 3 4]:## _
A(1, :) = [2 1] _
_
##gray|% [3 1; 2 4]:## _
A(:, 1) = [3 2] ||A = t(array(1:4, dim=c(2, 2))) _
_
A[1, ] = c(2, 1) _
A[, 1] = c(3, 2)||A = np.array([[1, 2], [3, 4]]) _
_
A[0, :] = [2, 1] _
##gray|# or## _
A[0] = [2, 1] _
_
A[:, 0] = [3, 2]||A = [1 2; 3 4] _
_
A[1, :] = [2 1] _
A[:, 1] = [3; 2]||
||# array-2d-update-subarray[#array-2d-update-subarray-note update subarray]||A = ones(3, 3) _
A(1:2, 1:2) = 2 * ones(2, 2) _
##gray|% or just:## _
A(1:2, 1:2) = 2||A = array(1, dim=c(3, 3)) _
A[1:2, 1:2] = array(2, dim=c(2, 2)) _
##gray|# or just:## _
A[1:2, 1:2] = 2||A = np.ones([3, 3]) _
A[0:2, 0:2] = 2 * np.ones([2, 2])||A = ones(3, 3) _
A[1:2, 1:2] = 2 * ones(2, 2)||
||# array-2d-out-of-bounds[#array-2d-out-of-bounds-note out-of-bounds behavior]||A = [2 4; 6 8] _
_
##gray|% error:## _
x = A(3, 1) _
_
##gray|% becomes 3x2 array with zero at (3, 2):## _
A(3, 1) = 9||##gray|//Lookups and updates both cause subscript out of bounds error.//##||##gray|//Lookups and updates both raise an// IndexError //exception.//##||##gray|BoundsError##||
||# array-2d-slice-subarray[#array-2d-slice-subarray-note slice subarray]||A = reshape(1:16, 4, 4)’ _
_
##gray|% top left 2x2 subarray:## _
A(1:2, 1:2) _
_
##gray|% bottom right 2x2 subarray:## _
A(end-1:end, end-1:end) _
_
##gray|% 2x2 array containing corners:## _
A([1 4], [1 4]) _
A([1 end], [1 end])||A = t(array(1:16, dim=c(4, 4))) _
_
##gray|# top left 2x2 subarray:## _
A[1:2, 1:2] _
_
##gray|# bottom right 2x2 subarray:## _
A[-1:-2, -1:-2] _
_
##gray|# 2x2 array containing corners:## _
A[c(1, 4), c(1, 4)]||A = np.array(range(1, 17)).reshape(4, 4) _
_
##gray|# top left 2x2 subarray:## _
A[0:2, 0:2] _
_
##gray|# bottom right 2x2 subarray:## _
A[2:, 2:]||A = reshape(1:16, 4, 4) _
_
A[1:2, 1:2] _
_
A[3:4, 3:4]||
||# array-2d-transpose[#array-2d-transpose-note transpose]||A = [1 2; 3 4] _
_
transpose(A)||A = array(c(1, 2, 3, 4), dim=c(2, 2)) _
t(A)||A = np.array([[1, 2], [3, 4]]) _
A.transpose() _
A.T||A = [1 2; 3 4] _
_
transpose(A)||
||# array-2d-flip[#array-2d-flip-note flip]||##gray|% [ 2 1; 4 3]:## _
fliplr([1 2; 3 4]) _
_
##gray|% [3 4; 1 2]:## _
flipud([1 2; 3 4])||##gray|# install.packages(‘pracma’):## _
require(pracma) _
_
A = t(array(1:4, dim=c(2, 2))) _
_
fliplr(A) _
flipud(A)||A = np.array([[1, 2], [3, 4]]) _
_
np.fliplr(A) _
np.flipud(A)||##gray|# [2 1; 4 3]:## _
flipdim([1 2; 3 4], 2) _
_
##gray|# [3 4; 1 2]:## _
flipdim([1 2; 3 4], 1)||
||# array-2d-circular-shift[#array-2d-circular-shift-note circular shift] _
_
##gray|//along columns, along rows//##||A = [1 2; 3, 4] _
_
##gray|% [3 4; 1 2]:## _
circshift(A, 1) _
_
##gray|% [2 1; 4 3]:## _
circshift(A, 1, 2) _
_
##gray|% The 2nd argument can be any integer; negative values shift _
% in the opposite direction.##||##gray|# install.packages(‘pracma’):## _
require(pracma) _
_
A = t(array(1:4, dim=c(2, 2))) _
_
circshift(A, c(1, 0)) _
circshift(A, c(0, 1))||A = np.array([[1, 2], [3, 4]]) _
_
np.roll(A, 1, axis=0) _
np.roll(A, 1, axis=1)||circshift([1 2; 3 4], [1, 0]) _
circshift([1 2; 3 4], [0, 1])||
||# array-2d-rotate[#array-2d-rotate-note rotate] _
##gray|//clockwise, counter-clockwise//##||A = [1 2; 3 4] _
_
##gray|% [3 1; 4 2]:## _
rot90(A, -1) _
_
##gray|% [2 4; 1 3]:## _
rot90(A) _
_
##gray|% set 2nd arg to 2 for 180 degree rotation##||##gray|# install.packages(‘pracma’):## _
require(pracma) _
_
A = t(array(1:4, dim=c(2, 2))) _
_
rot90(A) _
rot90(A, -1) _
rot90(A, 2)||A = np.array([[1, 2], [3, 4]]) _
_
np.rot90(A) _
np.rot90(A, -1) _
np.rot90(A, 2)||A = [1 2; 3 4] _
_
rotr90(A) _
rotl90(A) _
rotr90(A, 2)||
||# array-2d-reduce[#array-2d-reduce-note reduce] _
##gray|//rows, columns//##||M = [1 2; 3 4] _
_
##gray|% sum each row:## _
cellfun(@sum, num2cell(M, 2)) _
_
##gray|% sum each column:## _
cellfun(@sum, num2cell(M, 1)) _
_
##gray|% sum(M, 2) and sum(M, 1) also sum rows and columns##||M = matrix(c(1, 2, 3, 4), nrow=2) _
_
##gray|# sum each row:## _
apply(M, 1, sum) _
_
##gray|# sum each column:## _
apply(M, 2, sum)||M = np.array([[1, 2], [3, 4]]) _
_
np.add.reduce(A, 1) _
_
np.add.reduce(A, 0) _
_
##gray|# np.add is a built-in universal function. All universal functions have a reduce method.## _
_
##gray|# np.sum(A, 1,) and np.sum(A, 0) also sum rows and columns##||A = [1 2; 3 4] _
_
##gray|[3; 7]:## _
reducedim(+, A, [2], 0) _
_
##gray|[4 6]:## _
reducedim(+, A, [1], 0)||
||||||||||~ # three-d-arrays[#three-d-arrays-note three dimensional arrays]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# array-3d-construct-seq[#array-3d-construct-seq-note construct from sequence]||reshape([1 2 3 4 5 6 7 8], 2, 2, 2)||array(seq(1, 8), dim=c(2, 2, 2))||np.array(range(1, 9)).reshape(2, 2, 2)||reshape(1:8, 2, 2, 2)||
||# array-3d-construct-nested-seq[#array-3d-construct-nested-seq-note construct from nested sequences]||##gray|//none//##||##gray|//none//##||np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])|| ||
||# array-3d-construct-2d-arrays[#array-3d-construct-2d-arrays-note construct 3d array from 2d arrays]||A = [1, 2; 3, 4] _
A(:,:,2) = [5, 6; 7, 8]|| || ||A = Array{Float64}(2, 2, 2) _
A[:, :, 1] = [1 2; 3 4] _
A[:, :, 2] = [5 6; 7 8]||
||# array-3d-permute-axes[#array-3d-permute-axes-note permute axes]||A = reshape([1 2 3 4 5 6 7 8], 2, 2, 2) _
_
##gray|% swap 2nd and 3rd axes:## _
permute(A, [1 3 2])||A = array(1:8, dim=c(2, 2, 2)) _
_
##gray|# swap 2nd and 3rd axes:## _
aperm(A, perm=c(1, 3, 2))||A = np.array(range(1, 9)).reshape(2, 2, 2) _
_
##gray|# swap 2nd and 3rd axes:## _
A.transpose((0, 2, 1))||A = reshape(1:8, 2, 2, 2) _
_
##gray|# swap 2nd and 3rd axes:## _
reshape(A, [1, 3, 2])||
||# array-3d-flip[#array-3d-flip-note flip]||A = reshape([1 2 3 4 5 6 7 8], 2, 2, 2) _
_
flipdim(A, 3)||##gray|//none//##||##gray|//none//##||A = reshape(1:8, 2, 2, 2) _
_
flipdim(A, 3)||
||# array-3d-circular-shift[#array-3d-circular-shift-note circular shift]||A = reshape([1 2 3 4 5 6 7 8], 2, 2, 2) _
_
##gray|% 3rd arg specifies axis:## _
circshift(A, 1, 3)||##gray|//none//##||A = np.array(range(1, 9)).reshape(2, 2, 2) _
_
np.roll(A, 1, axis=2)||A = reshape(1:8, 2, 2, 2) _
_
circshift(A, [0, 0, 1])||
||||||||||~ # dictionaries[#dictionaries-note dictionaries]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# dict-literal[#dict-literal-note literal] _
@< >@||##gray|% no literal; use constructor:## _
d = struct(‘n’, 10, ‘avg’, 3.7, ‘sd’, 0.4) _
_
##gray|% or build from two cell arrays:## _
d = cell2struct({10 3.7 0.4}, {’n’ ‘avg’ ‘sd’}, 2)||##gray|# keys are ‘n’, ‘avg’, and ‘sd’:## _
d = list(n=10, avg=3.7, sd=0.4) _
_
##gray|# keys are 1, 2, and 3:## _
d2 = list(‘do’, ‘re’, ‘mi’)||d = {’n’: 10, ‘avg’: 3.7, ‘sd’: 0.4}||d = Dict(“n”=>10.0, “avg”=>3.7, “sd”=>0.4)||
||# dict-size[#dict-size-note size] _
@< >@||length(fieldnames(d))||length(d)||len(d)||length(d)||
||# dict-lookup[#dict-lookup-note lookup] _
@< >@||d.n _
getfield(d, ‘n’)||d’n’ _
_
##gray|# if ‘n’ is a key:## _
d$n||d[‘n’]|| ||
||# dict-update[#dict-update-note update] _
@< >@||d.var = d.sd@@2@@||d$var = d$sd@@@@2||d[‘var’] = d[‘sd’]@@**@@2|| ||
||# dict-missing-key[#dict-missing-key-note missing key behavior] _
@< >@||##gray|//error//##||NULL||##gray|//raises// KeyError##|| ||
||# dict-is-key-present[#dict-is-key-present-note is key present] _
@< >@||isfield(d, ‘var’)||is.null(d$var)||’var’ in d||haskey(d, “var”)||
||# dict-delete[#dict-delete-note delete] _
@< >@||d = rmfield(d, ‘sd’)||d$sd = NULL||del(d[‘sd’])|| ||
||# dict-iterate[#dict-iterate-note iterate]||for i = 1:numel(fieldnames(d)) _
@< >@k = fieldnames(d){i} _
@< >@v = d.(k) _
@< >@##gray|//code//## _
end||for (k in names(d)) { _
@< >@v = dk _
@< >@##gray|//code//## _
}||for k, v in d.iteritems(): _
@< >@##gray|//code//##|| ||
||# dict-keys-values-arrays[#dict-keys-values-arrays-note keys and values as arrays]||##gray|% these return cell arrays:## _
fieldnames(d) _
struct2cell(d)||names(d) _
unlist(d, use.names=F)||d.keys() _
d.values()|| ||
||# dict-merge[#dict-merge-note merge]||##gray|//none//##||d1 = list(a=1, b=2) _
d2 = list(b=3, c=4) _
##gray|# values of first dictionary take precedence:## _
d3 = c(d1, d2)||d1 = {’a’:1, ‘b’:2} _
d2 = {’b’:3, ‘c’:4} _
d1.update(d2)|| ||
||||||||||~ # functions[#functions-note functions]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# def-func[#def-func-note define function]||function add(x, y) _
@< >@x + y _
end||add = function(x, y) {x + y}|| ||function add(x,y) _
@< >@x + y _
end _
_
##gray|# optional syntax when body is an expression:## _
add(x, y) = x + y||
||# invoke-func[#invoke-func-note invoke function] _
@< >@||add(3, 7)||add(3, 7)|| ||add(3, 7)||
||# nested-func[#nested-func-note nested function]||function ret1 = add3(x, y, z) _
@< >@function ret2 = add2(x, y) _
@< >@@< >@ret2 = x + y; _
@< >@end _
_
@< >@ret1 = add2(x, y) + z; _
end||add3 = function(x, y, z) { _
@< >@add2 = function(x, y) { x + y } _
@< >@add2(x, y) + z _
}|| ||function add3(x, y, z) _
@< >@function add2(x2, y2) _
@< >@@< >@x2 + y2 _
@< >@end _
@< >@add2(x, y) + z _
end||
||# missing-arg[#missing-arg-note missing argument behavior]||##gray|//raises error if code with the parameter that is missing an argument is executed//##||##gray|//raises error//##|| ||##gray|//raises// MethodError##||
||# extra-arg[#extra-arg-note extra argument behavior] _
@< >@||##gray|//ignored//##||##gray|//raises error//##|| ||##gray|//raises// MethodError##||
||# default-arg[#default-arg-note default argument]||function mylog(x, base=10) _
@< >@log(x) / log(base) _
end||mylog = function(x,base=10) { _
@< >@log(x) / log(base) _
}|| || ||
||# variadic-func[#variadic-func-note variadic function]||function s = add(varargin) _
@< >@if nargin == 0 _
@< >@@< >@s = 0 _
@< >@else _
@< >@@< >@r = add(varargin{2:nargin}) _
@< >@@< >@s = varargin{1} + r _
@< >@end _
end||add = function (@@…@@) { _
@< >@a = list(@@…@@) _
@< >@if (length(a) == 0) _
@< >@@< >@return(0) _
@< >@s = 0 _
@< >@for(i in 1:length(a)) { _
@< >@@< >@s = s + ai _
@< >@} _
@< >@return(s) _
}|| || ||
||# retval[#retval-note return value]||function ret = add(x, y) _
@< >@ret = x + y; _
end _
_
##gray|% If a return variable is declared, the _
% value assigned to it is returned. Otherwise _
% the value of the last statement will be _
% used if it does not end with a semicolon.##||##gray|return //argument or last expression evaluated.// NULL //if// return //called without an argument.//##|| ||##gray|return //argument or last expression evaluated.// Void //if// return //called without an argument.//##||
||# multiple-retval[#multiple-retval-note multiple return values]||function [x, y] = first_two(a) _
@< >@x = a(1); _
@< >@y = a(2); _
end _
_
##gray|% sets first to 7; second to 8:## _
[first, second] = firsttwo([7 8 9])|| || ||function firsttwo(a) _
@< >@a[1], a[2] _
end _
_
x, y = first_two([1, 2, 3])||
||# anonymous-func-literal[#anonymous-func-literal-note anonymous function literal]||##gray|% body must be an expression:## _
@(x, y) x + y||function(x, y) {x + y}|| ||add = (x, y) -> x + y _
_
add = function(x, y) _
@< >@x + y _
end||
||# invoke-anonymous-func[#invoke-anonymous-func-note invoke anonymous function]|| || || ||add(1, 2)||
||# closure[#closure-note closure]|| ||make_counter = function() { _
@< >@i = 0 _
@< >@function() { _
@< >@@< >@i @@<<@@- i + 1 _
@< >@@< >@i _
@< >@} _
}|| || ||
||# func-as-val[#func-as-val-note function as value] _
@< >@||@add||add|| ||add||
||# overload-operator[#overload-operator-note overload operator]|| || || || ||
||# call-op-like-func[#call-op-like-func-note call operator like function]|| ||@@+@@(3, 7)|| ||+(3, 7)||
||||||||||~ # execution-control[#execution-control-note execution control]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# if[#if-note if]||if (x > 0) _
@< >@disp(‘positive’) _
elseif (x < 0) _
@< >@disp(‘negative’) _
else _
@< >@disp(‘zero’) _
end||if (x > 0) { _
@< >@print(‘positive’) _
} else if (x < 0) { _
@< >@print(‘negative’) _
} else { _
@< >@print(‘zero’) _
}||if x > 0: _
@< >@print(‘positive’) _
elif x < 0: _
@< >@print(‘negative’) _
else: _
@< >@print(‘zero’)||if x > 0 _
@< >@println(“positive”) _
elseif x < 0 _
@< >@println(“negative”) _
else _
@< >@println(“zero”) _
end||
||# while[#while-note while]||i = 0 _
while (i < 10) _
@< >@i = i + 1 _
@< >@disp(i) _
end||while (i < 10) { _
@< >@i = i + 1 _
@< >@print(i) _
}||while i < 10: _
@< >@i += 1 _
@< >@print(i)||i = 0 _
while i < 10 _
@< >@i += 1 _
@< >@println(i) _
end||
||# for[#for-note for]||for i = 1:10 _
@< >@disp(i) _
end||for (i in 1:10) { _
@< >@print(i) _
}||for i in range(1,11): _
@< >@print(i)||for i = 1:10 _
@< >@println(i) _
end||
||# break-continue[#break-continue-note break/continue] _
@< >@||break continue||break next||break continue||break continue||
||# raise-exc[#raise-exc-note raise exception] _
@< >@||error(‘%s’, ‘failed’)||stop(‘failed’)||raise Exception(‘failed’)||throw(“failed”)||
||# handle-exc[#handle-exc-note handle exception]||try _
@< >@error(‘failed’) _
catch err _
@< >@disp(err) _
end||tryCatch( _
@< >@stop(‘failed’), _
@< >@error=function(e) print(message(e)))||try: _
@< >@raise Exception(‘failed’) _
except Exception as e: _
@< >@print(e)|| ||
||||||||||~ # file-handle[#file-handle-note file handles]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# std-file-handles[#std-file-handles-note standard file handles]||0 1 2 _
_
##gray|% Octave has predefined variables _
% containing the above descriptors:## _
stdin stdout stderr||stdin() stdout() stderr()||sys.stdin sys.stdout sys.stderr||STDIN STDOUT STDERR||
||# read-line-stdin[#read-line-stdin-note read line from stdin]||line = input(‘‘, ‘s’)||line = readLines(n=1)||line = sys.stdin.readline()||line = readline()||
||# write-line-stdout[#write-line-stdout-note write line to stdout]||fprintf(1, ‘hello\n’)||cat(“hello\n”) _
_
writeLines(“hello”)||print(‘hello’)||println(“hello”)||
||# printf[#printf-note write formatted string to stdout]||fprintf(1, ‘%.2f\n’, pi)||cat(sprintf(“%.2f\n”, pi))||import math _
_
print(‘%.2f’ % math.pi)|| ||
||# open-file[#open-file-note open file for reading]||f = fopen(‘/etc/hosts’) _
if (f == -1) _
@< >@error(‘failed to open file’) _
end||f = file(“/etc/hosts”, “r”)||f = open(‘/etc/hosts’)||f = open(“/etc/hosts”)||
||# open-file-write[#open-file-write-note open file for writing]||if ((f = fopen(‘/tmp/test’, ‘w’) == -1) _
@< >@error(‘failed to open file’) _
endif||f = file(“/tmp/test”, “w”)||f = open(‘/tmp/test’, ‘w’)||f = open(“/etc/hosts”, “w”)||
||# open-file-append[#open-file-append-note open file for appending]||if ((f = fopen(‘/tmp/err.log’, ‘a’) == -1) _
@< >@error(‘failed to open file’) _
endif||f = file(“/tmp/err.log”, “a”)||f = open(‘/tmp/err.log’, ‘a’)||f = open(“/tmp/err.log”, “a”)||
||# close-file[#close-file-note close file]||fclose(f)||close(f)||f.close()||close(f)||
||# io-err[#io-err-note i/o errors]||##gray|fopen //returns -1;// fclose //throws an error//##|| ||##gray|//raise// IOError //exception//##|| ||
||# read-line[#read-line-note read line]||line = fgets(f)||line = readLines(f, n=1)||line = f.readline()||line = readline(f)||
||# file-iterate[#file-iterate-note iterate over file by line]||while(!feof(f)) _
@< >@line = fgets(f) _
@< >@puts(line) _
endwhile|| ||for line in f: _
@< >@print(line)|| ||
||# read-file-array[#read-file-array-note read file into array of strings]|| ||lines = readLines(f)||lines = f.readlines()||lines = readlines(f)||
||# write-str[#write-str-note write string]||fputs(f, ‘lorem ipsum’)||cat(“lorem ipsum”, file=f)||f.write(‘lorem ipsum’)||write(f, “lorem ipsum”)||
||# write-line[#write-line-note write line]||fputs(f, ‘lorem ipsum\n’)||writeLines(“lorem ipsum”, con=f)||f.write(‘lorem ipsum\n’)|| ||
||# flush[#flush-note flush file handle]||fflush(f)||flush(f)||f.flush()|| ||
||# seek[#seek-note file handle position] _
##gray|//get, set//##||ftell(f) _
_
##gray|% 3rd arg can be SEEKCUR or SEEKEND## _
fseek(f, 0, SEEK_SET)||seek(f) _
_
##gray|# sets seek point to 12 bytes after start; _
origin can also be “current” or “end”## _
seek(f, where=0, origin="start”)||f.tell() _
_
f.seek(0)|| ||
||# redirect-stdout-to-file[#redirect-stdout-to-file-note redirect stdout to file]|| ||sink(“foo.txt”)|| || ||
||write variables to file||A = [1 2; 3 4] _
B = [4 3; 2 1] _
_
save(‘data.mdata’, ‘A’, ‘B’)||A = matrix(c(1, 3, 2, 4), nrow=2) _
B = matrix(c(4, 2, 3, 1), nrow=2) _
_
save(A, B, file=’data.rdata’)||A = np.matrix([[1, 2], [3, 4]]) _
B = np.matrix([[4, 3], [2, 1]]) _
_
##gray|# Data must be of type np.array;## _
##gray|# file will have .npz suffix:## _
np.savez(‘data’, A=A, B=B)|| ||
||read variables from file||##gray|% puts A and B in scope:## _
load(‘data.mdata’) _
_
##gray|% puts just A in scope:## _
load(‘data.mdata’, ‘A’)||##gray|# puts A and B in scope:## _
load(‘data.rdata’)||data = np.load(‘data.npz’) _
A = data[‘A’] _
B = data[‘B’]|| ||
||write all variables in scope to file||save(‘data.txt’)||save.image(‘data.txt’)|| || ||
||||||||||~ # directories[#directories-note directories]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# working-dir[#working-dir-note working directory] _
##gray|//get, set//##||pwd _
_
cd(‘/tmp’)||getwd() _
_
setwd(“/tmp”)||os.path.abspath(‘.’) _
_
os.chdir(‘/tmp’)|| ||
||# build-pathname[#build-pathname-note build pathname]||fullfile(‘/etc’, ‘hosts’)||file.path(“/etc”, “hosts”)||os.path.join(‘/etc’, ‘hosts’)|| ||
||# dirname-basename[#dirname-basename-note dirname and basename]||[dir, base] = fileparts(‘/etc/hosts’)||dirname(“/etc/hosts”) _
basename(“/etc/hosts”)||os.path.dirname(‘/etc/hosts’) _
os.path.basename(‘/etc/hosts’)|| ||
||# absolute-pathname[#absolute-pathname-note absolute pathname]|| ||normalizePath(“..”)||os.path.abspath(‘..’)|| ||
||# iterate-dir[#iterate-dir-note iterate over directory by file]||##gray|% lists /etc:## _
ls(‘/etc’) _
_
##gray|% lists working directory:## _
ls()||##gray|# list.files() defaults to working directory## _
for (path in list.files(‘/etc’)) { _
@< >@print(path) _
}||for filename in os.listdir(‘/etc’): _
@< >@print(filename)|| ||
||# glob-paths[#glob-paths-note glob paths]||glob(‘/etc/’)||Sys.glob(‘/etc/’)||import glob _
_
glob.glob(‘/etc/’)|| ||
||||||||||~ # processes-environment[#processes-environment-note processes and environment]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# cmd-line-arg[#cmd-line-arg-note command line arguments]||##gray|% does not include interpreter name:## _
argv()||##gray|# first arg is name of interpreter:## _
commandArgs() _
_
##gray|# arguments after @@–@@args only:## _
commandArgs(TRUE)||sys.argv||ARGS||
||# env-var[#env-var-note environment variable] _
##gray|//get, set//##||getenv(‘HOME’) _
_
setenv(‘PATH’, ‘/bin’)||Sys.getenv(“HOME”) _
_
Sys.setenv(PATH=”/bin”)||os.getenv(‘HOME’) _
_
os.environ[‘PATH’] = ‘/bin’||ENV[“HOME”] _
_
ENV[“PATH”] = “/bin”||
||# exit[#exit-note exit] _
@< >@||exit(0)||quit(save="no”, status=0)||sys.exit(0)||exit(0)||
||# external-cmd[#external-cmd-note external command]||if (shell_cmd(‘ls -l /tmp’)) _
@< >@error(‘ls failed’) _
endif||if (system(“ls -l /tmp”)) { _
@< >@stop(“ls failed”) _
}||if os.system(‘ls -l /tmp’): _
@< >@raise Exception(‘ls failed’)|| ||
||# cmd-subst[#cmd-subst-note command substitution]|| || || ||s = readall(ls)||
||||||||||~ # libraries-namespaces[#libraries-namespaces-note libraries and namespaces]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# load-lib[#load-lib-note load library]||##gray|//When a function is invoked, MATLAB searches the library path for a file with the same name and a// .m //suffix. Other functions defined in the file are not visible outside the file.//##||##gray|# quoting the name of the package is optional:## _
require(“foo”) _
##gray|# or: ## _
library(“foo”) _
_
##gray|# if the package does not exist, require returns false, and library raises an error.##||import foo||include(“foo.jl”)||
||# list-lib[#list-lib-note list loaded libraries]||##gray|//none//##||search()||dir()|| ||
||# lib-path[#lib-path-note library search path]||path() _
addath(‘~/foo’) _
rmpath(‘~/foo’)||.libPaths()||sys.path|| ||
||# source-file[#source-file-note source file] _
@< >@||run(‘foo.m’)||source(“foo.r”)||##gray|//none//##|| ||
||# install-pkg[#install-pkg-note install package]||##gray|% Octave: how to install package _
% downloaded from Octave-Forge: ## _
pkg install foo-1.0.0.tar.gz ||install.packages(“ggplot2”)||$ pip install scipy|| ||
||# load-pkg[#load-pkg-note load package library]||##gray|% Octave:## _
pkg load foo||require(“foo”) _
##gray|# or:## _
library(“foo”)||import foo|| ||
||# list-pkg[#list-pkg-note list installed packages]||##gray|% Octave:## _
pkg list||library() _
installed.packages()||$ pip freeze|| ||
||||||||||~ # reflection[#reflection-note reflection]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# data-type[#data-type-note data type]||class(x)||class(x) _
##gray|# often more informative:## _
str(x)||type(x)||typeof(x)||
||# attr[#attr-note attributes]||##gray|% if x holds an object:## _
x||attributes(x)||[m for m in dir(x) _
@< >@if not callable(getattr(o,m))]||fieldnames(x)||
||# methods[#method-note methods]||##gray|% if x holds an object:## _
methods(x)||##gray|//none; objects are implemented by functions which dispatch based on type of first arg//##||[m for m in dir(x) _
@< >@if callable(getattr(o,m))]||methods(x)||
||# var-in-scope[#var-in-scope-note variables in scope]||who() _
_
##gray|% with size and type:## _
whos()||objects() _
ls() _
_
##gray|# with type and description:## _
ls.str()||dir()||whos()||
||# undef-var[#undef-var-note undefine variable] _
@< >@||clear(‘x’)||rm(v)||del(x)||##gray|//none//##||
||# undef-all-var[#undef-all-var-note undefine all variables]||clear -a||rm(list=objects())|| ||##gray|//none//##||
||# eval[#eval-note eval] _
@< >@||eval(‘1 + 1’)||eval(parse(text=’1 + 1’))||eval(‘1 + 1’)||eval(parse(“1 + 1”))||
||# func-doc[#func-doc-note function documentation]||help tan||help(tan) _
?tan||math.tan.@@doc@@||?tan||
||# ls-lib[#ls-lib-note list library functions]||##gray|//none//##||ls(“package:moments”)||dir(stats)||whos(Base)||
||# grep-doc[#grep-doc-note search documentation]||docsearch tan||??tan||$ pydoc -k tan||apropos(“tan”)||
||||||||||~ # debugging[#debugging-note debugging]||
||~ ||~ [#matlab matlab]||~ [#r r]||~ [#numpy numpy]||~ [#julia julia]||
||# benchmark-code[#benchmark-code-note benchmark code]||tic _
n = 0 _
for i = 1:10001000 _
@< >@n = n + 1; _
end _
toc|| ||import timeit _
_
timeit.timeit(‘i += 1’, _
@< >@’i = 0’, _
@< >@number=1000000)|| ||
||~ ||~ ##EFEFEF|@@_______________________________________________@@##||~ ##EFEFEF|@@____________________________________________@@##||~ ##EFEFEF|@@____________________________________________@@##||~ ##EFEFEF|@@_______________________________________________@@##||
tables] | import and export] | relational algebra] | aggregation]
vectors] | matrices] | sparse matrices] | optimization] | polynomials] | descriptive statistics] | distributions] | linear regression] | statistical tests] | time series] | fast fourier transform] | clustering] | images] | sound]
univariate charts] | bivariate charts] | multivariate charts]
# general-note + [#top General]
# version-used-note ++ [#version-used version used]
The version of software used to check the examples in the reference sheet.
# show-version-note ++ [#show-version show version]
How to determine the version of an installation.
# implicit-prologue-note ++ [#implicit-prologue implicit prologue]
Code which examples in the sheet assume to have already been executed.
r:
The {{ggplot2}} library must be installed and loaded to use the plotting functions {{qplot}} and {{ggplot}}.
# grammar-invocation-note + [#grammar-invocation Grammar and Invocation]
# interpreter-note ++ [#interpreter interpreter]
How to invoke the interpreter on a script.
# repl-note ++ [#repl repl]
How to launch a command line read-eval-print loop for the language.
r:
R installations come with a GUI REPL.
The shell {{zsh}} has a built-in command {{r}} which re-runs the last command. Shell built-ins take precedence over external commands, but one can invoke the R REPL with:
# cmd-line-program-note ++ [#cmd-line-program command line program]
How to pass the code to be executed to the interpreter as a command line argument.
# env-var-note ++ [#env-var environment variables]
How to get and set an environment variable.
# block-delimiters-note ++ [#block-delimiters block delimiters]
Punctuation or keywords which define blocks.
matlab:
The list of keywords which define blocks is not exhaustive. Blocks are also defined by
- //switch//, //case//, //otherwise//, //endswitch//
- //unwindprotect//, //unwindprotectcleanup//, //endunwind_protect//
- //try//, //catch//, //endtrycatch//
# stmt-separator-note ++ [#stmt-separator statement separator]
How statements are separated.
matlab:
Semicolons are used at the end of lines to suppress output. Output echoes the assignment performed by a statement; if the statement is not an assignment the value of the statement is assigned to the special variable {{ans}}.
In Octave, but not MATLAB, newlines are not separators when preceded by a backslash.
# eol-comment-note ++ [#eol-comment end-of-line comment]
Character used to start a comment that goes to the end of the line.
octave:
Octave, but not MATLAB, also supports shell-style comments which start with {{#}}.
# var-expr-note + [#var-expr Variables and Expressions]
# assignment-note ++ [#assignment assignment]
r:
Traditionally <- was used in R for assignment. Using an = for assignment was introduced in version 1.4.0 sometime before 2002. -> can also be used for assignment:
# compound-assignment-note ++ [#compound-assignment compound assignment]
The compound assignment operators.
octave:
Octave, but not MATLAB, has compound assignment operators for arithmetic and bit operations:
code += -= *= /= **= ^= &= |= /code
Octave, but not MATLAB, also has the C-stye increment and decrement operators {{++}} and {{@@–@@}}, which can be used in prefix and postfix position.
# incr-decr-note ++ [#incr-decr increment and decrement operator]
The operator for incrementing the value in a variable; the operator for decrementing the value in a variable.
# null-note ++ [#null null]
matlab:
{{NaN}} can be used for missing numerical values. Using a comparison operator on it always returns false, including {{NaN == NaN}}. Using a logical operator on {{NaN}} raises an error.
octave:
Octave, but not MATLAB, provides {{NA}} which is a synonym of {{NaN}}.
r:
Relational operators return {{NA}} when one of the arguments is {{NA}}. In particular {{NA == NA}} is {{NA}}. When acting on values that might be {{NA}}, the logical operators observe the rules of [http://en.wikipedia.org/wiki/Ternary_logic ternary logic], treating {{NA}} is the unknown value.
# null-test-note ++ [#null-test null test]
How to test if a value is null.
octave:
Octave, but not MATLAB, has {{isna}} and {{isnull}}, which are synonyms of {{isnan}} and {{isempty}}.
# cond-expr-note ++ [#cond-expr conditional expression]
A conditional expression.
# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]
# true-false-note ++ [#true-false true and false]
The boolean literals.
matlab:
//true// and //false// are functions which return matrices of ones and zeros of type //logical//. If no arguments are specified they return single entry matrices. If one argument is provided, a square matrix is returned. If two arguments are provided, they are the row and column dimensions.
# falsehoods-note ++ [#falsehoods falsehoods]
Values which evaluate to false in a conditional test.
matlab:
When used in a conditional, matrices evaluate to false unless they are nonempty and all their entries evaluate to true. Because strings are matrices of characters, an empty string (‘‘ or ““) will evaluate to false. Most other strings will evaluate to true, but it is possible to create a nonempty string which evaluates to false by inserting a null character; e.g. “false\000”.
r:
When used in a conditional, a vector evaluates to the boolean value of its first entry. Using a vector with more than one entry in a conditional results in a warning message. Using an empty vector in a conditional, //c()// or //NULL//, raises an error.
# logical-op-note ++ [#logical-op logical operators]
The boolean operators.
octave:
Octave, but not MATLAB, also uses the exclamation point ‘!’ for negation.
# relational-op-note ++ [#relational-op relational operators]
The relational operators.
octave:
Octave, but not MATLAB, also uses {{!=}} for an inequality test.
# arith-op-note ++ [#arith-op arithmetic operators]
The arithmetic operators: addition, subtraction, multiplication, division, quotient, remainder.
matlab:
//mod// is a function and not an infix operator. //mod// returns a positive value if the first argument is positive, whereas //rem// returns a negative value.
# int-div-note ++ [#int-div integer division]
How to compute the quotient of two integers.
# int-div-zero-note ++ [#int-div-zero integer division by zero]
What happens when an integer is divided by zero.
# float-div-note ++ [#float-div float division]
How to perform float division, even if the arguments are integers.
# float-div-zero-note ++ [#float-div-zero float division by zero]
What happens when a float is divided by zero.
# power-note ++ [#power power]
octave:
Octave, but not MATLAB, supports {{@@**@@}} as a synonym of {{^}}.
# sqrt-note ++ [#sqrt sqrt]
The square root function.
# sqrt-negative-one-note ++ [#sqrt-negative-one sqrt(-1)]
The result of taking the square root of a negative number.
# transcendental-func-note ++ [#transcendental-func transcendental functions]
The standard transcendental functions.
# transcendental-const-note ++ [#transcendental-const transcendental constants]
Constants for //pi// and //e//.
# float-truncation-note ++ [#float-truncation float truncation]
Ways of converting a float to a nearby integer.
# absolute-val-note ++ [#absolute-val absolute value]
The absolute value and signum of a number.
# int-overflow-note ++ [#int-overflow integer overflow]
What happens when an expression evaluates to an integer which is too big to be represented.
# float-overflow-note ++ [#float-overflow float overflow]
What happens when an expression evaluates to a float which is too big to be represented.
# float-limits-note ++ [#float-limits float limits]
The [http://en.wikipedia.org/wiki/Machine_epsilon machine epsilon]; the largest representable float and the smallest (i.e. closest to negative infinity) representable float.
# complex-construction-note ++ [#complex-construction complex construction]
Literals for complex numbers.
# complex-decomposition-note ++ [#complex-decomposition complex decomposition]
How to decompose a complex number into its real and imaginary parts; how to decompose a complex number into its absolute value and argument; how to get the complex conjugate.
# random-num-note ++ [#random-num random number]
How to generate a random integer from a uniform distribution; how to generate a random float from a uniform distribution.
# random-seed-note ++ [#random-seed random seed]
How to set, get, and restore the seed used by the random number generator.
matlab:
At startup the random number generator is seeded using operating system entropy.
r:
At startup the random number generator is seeded using the current time.
numpy:
On Unix the random number generator is seeded at startup from /dev/random.
# bit-op-note ++ [#bit-op bit operators]
The bit operators left shift, right shift, and, or , xor, and negation.
matlab/octave:
{{bitshift}} takes a second argument which is positive for left shift and negative for right shift.
{{bitcmp}} takes a second argument which is the size in bits of the integer being operated on. Octave is not compatible with MATLAB in how the integer size is indicated.
r:
There is a library on CRAN called {{bitops}} which provides bit operators.
# strings-note + [#strings Strings]
# str-literal-note ++ [#str-literal literal]
The syntax for a string literal.
# str-newline-note ++ [#str-newline newline in literal]
Can a newline be included in a string literal? Equivalently, can a string literal span more than one line of source code?
octave:
Double quote strings are Octave specific.
A newline can be inserted into a double quote string using the backslash escape {{\n}}.
A double quote string can be continued on the next line by ending the line with a backslash. No newline is inserted into the string.
# str-esc-note ++ [#str-esc literal escapes]
Escape sequences for including special characters in string literals.
matlab:
C-style backslash escapes are not recognized by string literals, but they are recognized by the IO system; the string ‘foo\n’ contains 5 characters, but emits 4 characters when written to standard output.
# str-concat-note ++ [#str-concat concatenate]
How to concatenate strings.
# str-replicate-note ++ [#str-replicate replicate]
How to create a string which consists of a character of substring repeated a fixed number of times.
# index-substr-note ++ [#index-substr index of substring]
How to get the index of first occurrence of a substring.
# extract-substr-note ++ [#extract-substr extract substring]
How to get the substring at a given index.
octave:
Octave supports indexing string literals directly: {{’hello’(1:4)}}.
# split-note ++ [#split split]
How to split a string into an array of substrings. In the original string the substrings must be separated by a character, string, or regex pattern which will not appear in the array of substrings.
The split operation can be used to extract the fields from a field delimited record of data.
matlab:
Cell arrays, which are essentially [#tuples tuples], are used to store variable-length strings.
A two dimensional array of characters can be used to store strings of the same length, one per row. Regular arrays cannot otherwise be used to store strings.
# join-note ++ [#join join]
How to join an array of substrings into single string. The substrings can be separated by a specified character or string.
Joining is the inverse of splitting.
# trim-note ++ [#trim trim]
How to remove whitespace from the beginning and the end of a string.
Trimming is often performed on user provided input.
# pad-note ++ [#pad pad]
How to pad the edge of a string with spaces so that it is a prescribed length.
# num-to-str-note ++ [#num-to-str number to string]
How to convert a number to a string.
# str-to-num-note ++ [#str-to-num string to number]
How to convert a string to number.
# case-manipulation-note ++ [#case-manipulation translate case]
How to put a string into all caps. How to put a string into all lower case letters.
# sprintf-note ++ [#sprintf sprintf]
How to create a string using a printf style format.
# str-len-note ++ [#str-len length]
How to get the number of characters in a string.
# char-access-note ++ [#char-access character access]
How to get the character in a string at a given index.
octave:
Octave supports indexing string literals directly: {{’hello’(1)}}.
# chr-ord-note ++ [#chr-ord chr and ord]
How to convert an ASCII code to a character; how to convert a character to its ASCII code.
# regexes-note + [#regexes Regular Expressions]
# char-class-abbrevs-note ++ [#char-class-abbrevs character class abbreviations]
The supported character class abbreviations.
A character class is a set of one or more characters. In regular expressions, an arbitrary character class can be specified by listing the characters inside square brackets. If the first character is a circumflex {{^}}, the character class is all characters not in the list. A hyphen {{-}} can be used to list a range of characters.
matlab:
The C-style backslash escapes, which can be regarded as character classes which match a single character, are a feature of the regular expression engine and not string literals like in other languages.
# regex-anchors-note ++ [#regex-anchors anchors]
The supported anchors.
The {{<}} and {{>}} anchors match the start and end of a word respectively.
# regex-match-note ++ [#regex-match match test]
How to test whether a string matches a regular expression.
# case-insensitive-regex-match-note ++ [#case-insensitive-regex-match case insensitive match test]
How to perform a case insensitive match test.
# regex-subst-note ++ [#regex-subst substitution]
How to replace all substring which match a pattern with a specified string; how to replace the first substring which matches a pattern with a specified string.
# regex-backreference-note ++ [#regex-backreference backreference in match and substitution]
How to use backreferences in a regex; how to use backreferences in the replacement string of substitution.
# dates-time-note + [#dates-time Date and Time]
# current-date-time-note ++ [#current-date-time current date/time]
How to get the current date and time.
r:
{{Sys.time()}} returns a value of type {{POSIXct}}.
# date-time-type-note ++ [#date-time-type date/time type]
The data type used to hold a combined date and time value.
matlab:
The Gregorian calendar was introduced in 1582. The Proleptic Gregorian Calendar is sometimes used for earlier dates, but in the Proleptic Gregorian Calendar the year 1 CE is preceded by the year 1 BCE. The MATLAB epoch thus starts at the beginning of the year 1 BCE, but uses a zero to refer to this year.
# date-time-diff-type-note ++ [#date-time-diff-type date/time difference type]
The data type used to hold the difference between two date/time types.
# date-parts-note ++ [#date-parts get date parts]
How to get the year, the month as an integer from 1 through 12, and the day of the month from a date/time value.
octave:
In Octave, but not MATLAB, one can use index notation on the return value of a function:
code t = now datevec(t)(1) /code
# time-parts-note ++ [#time-parts get time parts]
How to get the hour as an integer from 0 through 23, the minute, and the second from a date/time value.
# build-date-time-note ++ [#build-date-time build date/time from parts]
How to build a date/time value from the year, month, day, hour, minute, and second as integers.
# date-to-str-note ++ [#date-to-str convert to string]
How to convert a date value to a string using the default format for the locale.
# strptime-note ++ [#strptime parse datetime]
How to parse a date/time value from a string in the manner of strptime from the C standard library.
# strftime-note ++ [#strftime format datetime]
How to write a date/time value to a string in the manner of strftime from the C standard library.
# tuples-note + [#tuples Tuples]
# tuple-type-note ++ [#tuple-type type]
The name of the data type which implements tuples.
# tuple-literal-note ++ [#tuple-literal literal]
How to create a tuple, which we define as a fixed length, inhomogeneous list.
# tuple-access-note ++ [#tuple-access lookup element]
How to access an element of a tuple.
# tuple-update-note ++ [#tuple-update update element]
How to change one of a tuple’s elements.
# tuple-len-note ++ [#tuple-len length]
How to get the number of elements in a tuple.
# arrays-note + [#arrays Arrays]
This section covers one-dimensional arrays which map integers to values.
[#multidimensional-arrays Multidimensional arrays] are a generalization which map tuples of integers to values.
[#vectors Vectors] and [#matrices matrices] are one-dimensional and two-dimensional arrays respectively containing numeric values. They support additional operations including the dot product, matrix multiplication, and norms.
Here are the data types covered in each section:
||~ section||~ matlab||~ r||~ numpy||~ julia|| ||[#arrays arrays]||matrix (ndims = 1)||vector||list|| || ||[#multidimensional-arrays multidimensional arrays]||matrix||array||np.array|| || ||[#vectors vectors]||matrix (ndims = 1)||vector||np.array (ndim = 1)|| || ||[#matrices matrices]||matrix (ndims = 2)||matrix||np.matrix|| ||
# array-elem-type-note ++ [#array-elem-type element type]
How to get the type of the elements of an array.
# permitted-array-elem-types-note ++ [#permitted-array-elem-types permitted element types]
Permitted data types for array elements.
matlab:
Arrays in Octave can only contain numeric elements.
Array literals can have a nested structure, but Octave will flatten them. The following literals create the same array:
code [ 1 2 3 [ 4 5 6] ] [ 1 2 3 4 5 6 ] /code
Logical values can be put into an array because //true// and //false// are synonyms for 1 and 0. Thus the following literals create the same arrays:
code [ true false false ] [ 1 0 0 ] /code
If a string is encountered in an array literal, the string is treated as an array of ASCII values and it is concatenated with other ASCII values to produce as string. The following literals all create the same string:
code [ ‘foo’, 98, 97, 114] [ ‘foo’, ‘bar’ ] ‘foobar’ /code
If the other numeric values in an array literal that includes a string are not integer values that fit into a ASCII byte, then they are converted to byte sized values.
r:
Array literals can have a nested structure, but R will flatten them. The following literals produce the same array of 6 elements:
code c(1,2,3,c(4,5,6)) c(1,2,3,4,5,6) /code
If an array literal contains a mixture of booleans and numbers, then the boolean literals will be converted to 1 (for TRUE and T) and 0 (for FALSE and F).
If an array literal contains strings and either booleans or numbers, then the booleans and numbers will be converted to their string representations. For the booleans the string representations are “TRUE’” and “FALSE”.
# array-literal-note ++ [#array-literal literal]
The syntax, if any, for an array literal.
matlab:
The array literal
code [1,’foo’,3] /code will create an array with 5 elements of class //char//.
r:
The array literal
will create an array of 3 elements of class //character//, which is the R string type.
# array-size-note ++ [#array-size size]
How to get the number of values in an array.
# array-empty-test-note ++ [#array-empty-test empty test]
# array-lookup-note ++ [#array-lookup lookup]
# array-update-note ++ [#array-update update]
# array-out-of-bounds-note ++ [#array-out-of-bounds out-of-bounds behavior]
# array-element-index-note ++ [#array-element-index index of element]
# array-slice-note ++ [#array-slice slice]
# array-slice-to-end-note ++ [#array-slice-to-end slice to end]
# array-concatenation-note ++ [#array-concatenation concatenate]
# array-replication-note ++ [#array-replication replicate]
# array-copy-note ++ [#array-copy copy]
How to make an address copy, a shallow copy, and a deep copy of an array.
After an address copy is made, modifications to the copy also modify the original array.
After a shallow copy is made, the addition, removal, or replacement of elements in the copy does not modify of the original array. However, if elements in the copy are modified, those elements are also modified in the original array.
A deep copy is a recursive copy. The original array is copied and a deep copy is performed on all elements of the array. No change to the contents of the copy will modify the contents of the original array.
# arithmetic-sequences-note + [#arithmetic-sequences Arithmetic Sequences]
An arithmetic sequence is a sequence of numeric values in which consecutive terms have a constant difference.
# arith-seq-diff-one-note ++ [#arith-seq-diff-one unit difference]
An arithmetic sequence with a difference of 1.
# arith-seq-diff-ten-note ++ [#arith-seq-diff-ten difference of 10]
An arithmetic sequence with a difference of 10.
# arith-seq-diff-tenth-note ++ [#arith-seq-diff-tenth difference of 0.1]
An arithmetic sequence with a difference of 0.1.
# arith-seq-computed-diff-note ++ [#arith-seq-computed-diff computed difference]
An arithmetic sequence where the difference is computed using the start and end values and the number of elements.
# iter-over-arith-seq-note ++ [#iter-over-arith-seq iterate]
How to iterate over an arithmetic sequence.
# arith-seq-to-array-note ++ [#arith-seq-to-array to array]
How to convert an arithmetic sequence to an array.
# two-d-arrays-note # three-d-arrays-note + [#two-d-arrays Multidimensional Arrays]
Multidimensional arrays are a generalization of arrays which map tuples of integers to values. All tuples in the domain of a multidimensional array have the same length; this length is the dimension of the array.
The multidimensional arrays described in this sheet are homogeneous, meaning that the values are all of the same type. This restriction allows the implementation to store the values of the multidimensional array in a contiguous region of memory without the use of references or points.
Multidimensional arrays should be contrasted with nested arrays. When arrays are nested, the innermost nested arrays contain the values and the other arrays contain references to arrays. The syntax for looking up a value is usually different:
nested:
a[1][2]
multidimensional:
a[1, 2] /code
# multidimensional-array-elem-type-note ++ [#multidimensional-array-elem-type element type]
How to get the type of the values stored in a multidimensional array.
r:
# 1d-array-literal-note ++ [#1d-array-literal literal—1d]
# 2d-array-literal-note ++ [#2d-array-literal literal—2d]
# 2d-construct-seq-note ++ [#2d-construct-seq construct from sequence—2d]
# 3d-construct-seq-note ++ [#3d-construct-seq construct from sequence—3d]
# 2d-construct-nested-seq-note ++ [#2d-construct-nested-seq construct from nested sequences—2d]
# 3d-construct-nested-seq-note ++ [#3d-construct-nested-seq construct from nested sequences—3d]
# 2d-construct-rows-note ++ [#2d-construct-rows construct from rows—2d]
# 2d-construct-columns-note ++ [#2d-construct-columns construct from columns—2d]
# 2d-construct-subarrays-note ++ [#2d-construct-subarrays construct from subarrays—2d]
# 3d-construct-2d-arrays-note ++ [#3d-construct-2d-arrays construct 3d array from 2d arrays]
# multidimensional-array-size-note ++ [#multidimensional-array-size size]
# 1d-lookup-note ++ [#1d-lookup lookup—1d]
# 2d-lookup-note ++ [#2d-lookup lookup—2d]
# 1d-lookup-2d-array-note ++ [#1d-lookup-2d-array 1d lookup on 2d array]
# 2d-update-note ++ [#2d-update update—2d]
# multidimensional-array-out-of-bounds-note ++ [#multidimensional-array-out-of-bounds out-of-bounds behavior]
# multidimensional-array-slice-note ++ [#multidimensional-array-slice slice]
# multidimensional-array-slice-to-end-note ++ [#multidimensional-array-slice-to-end slice to end]
# multidimensional-array-slice-subarray-note ++ [#multidimensional-array-slice-subarray slice subarray]
# multidimensional-array-transpose-note ++ [#multidimensional-array-transpose transpose]
# multidimensional-array-permute-axes-note ++ [#multidimensional-array-permute-axes permute axes]
# 2d-flip-note ++ [#2d-flip flip—2d]
# 3d-flip-note ++ [#3d-flip flip—3d]
++ circular shift—2d
++ rotate—2d
++ apply function element-wise
++ apply function to linear subarrays
# dictionaries-note + [#dictionaries Dictionaries]
# dict-literal-note ++ [#dict-literal literal]
The syntax for a dictionary literal.
# dict-size-note ++ [#dict-size size]
How to get the number of keys in a dictionary.
# dict-lookup-note ++ [#dict-lookup lookup]
How to use a key to lookup a value in a dictionary.
# dict-update-note ++ [#dict-update update]
How to add or key-value pair or change the value for an existing key.
# dict-missing-key-note ++ [#dict-missing-key missing key behavior]
What happens when looking up a key that isn’t in the dictionary.
# dict-delete-note ++ [#dict-delete delete]
How to delete a key-value pair from a dictionary.
# dict-iterate-note ++ [#dict-iterate iterate]
How to iterate over the key-value pairs.
# dict-keys-values-arrays-note ++ [#dict-keys-values-arrays keys and values as arrays]
How to get an array containing the keys; how to get an array containing the values.
# dict-merge-note ++ [#dict-merge merge]
How to merge two dictionaries.
# functions-note + [#functions Functions]
# def-func-note ++ [#def-func define function]
How to define a function.
# invoke-func-note ++ [#invoke-func invoke function]
How to invoke a function.
# nested-func-note ++ [#nested-func nested function]
# missing-arg-note ++ [#missing-arg missing argument behavior]
What happens when a function is invoked with too few arguments.
# extra-arg-note ++ [#extra-arg extra argument behavior]
What happens when a function is invoked with too many arguments.
# default-arg-note ++ [#default-arg default argument]
How to assign a default argument to a parameter.
# variadic-func-note ++ [#variadic-func variadic function]
How to define a function which accepts a variable number of arguments.
# retval-note ++ [#retval return value]
How the return value of a function is determined.
# multiple-retval-note ++ [#multiple-retval multiple return values]
How to return multiple values from a function.
# anonymous-func-literal-note ++ [#anonymous-func-literal anonymous function literal]
The syntax for an anonymous function.
# invoke-anonymous-func-note ++ [#invoke-anonymous-func invoke anonymous function]
# closure-note ++ [#closure closure]
# func-as-value-note ++ [#func-as-value function as value]
How to store a function in a variable.
# execution-control-note + [#execution-control Execution Control]
# if-note ++ [#if if]
How to write a branch statement.
# while-note ++ [#while while]
How to write a conditional loop.
# for-note ++ [#for for]
How to write a C-style for statement.
# break-continue-note ++ [#break-continue break/continue]
How to break out of a loop. How to jump to the next iteration of a loop.
# raise-exc-note ++ [#raise-exc raise exception]
How to raise an exception.
# handle-exc-note ++ [#handle-exc handle exception]
How to handle an exception.
# file-handle-note + [#file-handle File Handles]
# std-file-handles-note ++ [#std-file-handles standard file handles]
Standard input, standard output, and standard error.
# read-line-stdin-note ++ [#read-line-stdin read line from stdin]
# write-line-stdout-note ++ [#write-line-stdout write line to stdout]
How to write a line to stdout.
matlab:
The backslash escape sequence {{\n}} is stored as two characters in the string and interpreted as a newline by the IO system.
# printf-note ++ [#printf write formatted string to stdout]
# open-file-note ++ [#open-file open file for reading]
# open-file-write-note ++ [#open-file-write open file for writing]
# open-file-append-note ++ [#open-file-append open file for appending]
# close-file-note ++ [#close-file close file]
# io-err-note ++ [#io-err i/o errors]
# read-line-note ++ [#read-line read line]
# file-iterate-note ++ [#file-iterate iterate over file by line]
# read-file-array-note ++ [#read-file-array read file into array of strings]
# write-str-note ++ [#write-str write string]
# write-line-note ++ [#write-line write line]
# flush-note ++ [#flush flush file handle]
# seek-note ++ [#seek file handle position]
# redirect-stdout-to-file-note ++ [#redirect-stdout-to-file redirect stdout to file]
# directories-note + [#directories Directories]
# working-dir-note ++ [#working-dir working directory]
How to get and set the working directory.
# processes-environment-note + [#processes-environment Processes and Environment]
# cmd-line-arg-note ++ [#cmd-line-arg command line arguments]
How to get the command line arguments.
# env-var-note ++ [#env-var environment variables]
How to get and set and environment variable.
# libraries-namespaces-note + [#libraries-namespaces Libraries and Namespaces]
# load-lib-note ++ [#load-lib load library]
How to load a library.
# list-lib-note ++ [#list-lib list loaded libraries]
Show the list of libraries which have been loaded.
# lib-path-note ++ [#lib-path library search path]
The list of directories the interpreter will search looking for a library to load.
# source-file-note ++ [#source-file source file]
How to source a file.
r:
When sourcing a file, the suffix if any must be specified, unlike when loading library. Also, a library may contain a shared object, but a sourced file must consist of just R source code.
# install-pkg-note ++ [#install-pkg install package]
How to install a package.
# list-pkg-note ++ [#list-pkg list installed packages]
How to list the packages which have been installed.
# reflection-note + [#reflection Reflection]
# data-type-note ++ [#data-type data type]
How to get the data type of a value.
r:
For vectors {{class}} returns the //mode// of the vector which is the type of data contained in it. The possible modes are
- numeric
- complex
- logical
- character
- raw
Some of the more common class types for non-vector entities are:
- matrix
- array
- list
- factor
- data.frame
# attr-note ++ [#attr attributes]
How to get the attributes for an object.
r:
Arrays and vectors do not have attributes.
# method-note ++ [#methods methods]
How to get the methods for an object.
# var-in-scope-note ++ [#var-in-scope variables in scope]
How to list the variables in scope.
# undef-var-note ++ [#undef-var undefine variable]
How to undefine a variable.
# undef-all-var-note ++ [#undef-all-var undefine all variables]
How to undefine all variables.
# eval-note ++ [#eval eval]
How to interpret a string as source code and execute it.
# func-doc-note ++ [#func-doc function documentation]
How to get the documentation for a function.
# ls-lib-note ++ [#ls-lib list library functions]
How to list the functions and other definitions in a library.
# grep-doc-note ++ [#grep-doc search documentation]
How to search the documentation by keyword.
# debugging-note + [#debugging Debugging]
# benchmark-code-note ++ [#benchmark-code benchmark code]
How to benchmark code.
# matlab + [#top MATLAB]
[http://www.gnu.org/software/octave/doc/interpreter/ Octave Manual] [http://www.mathworks.com/help/techdoc/ MATLAB Documentation] [http://en.wikibooks.org/wiki/MATLAB_Programming/Differences_between_Octave_and_MATLAB Differences between Octave and MATLAB] [http://octave.sourceforge.net/packages.php Octave-Forge Packages]
The basic data type of MATLAB is a matrix of floats. There is no distinction between a scalar and a 1x1 matrix, and functions that work on scalars typically work on matrices as well by performing the scalar function on each entry in the matrix and returning the results in a matrix with the same dimensions. Operators such as the logical operators (‘&’ ‘|’ ‘!’), relational operators (‘==’, ‘!=’, ‘<’, ‘>’), and arithmetic operators (‘+’, ‘-’) all work this way. However the multiplication ‘‘ and division ‘/’ operators perform matrix multiplication and matrix division, respectively. The {{.}} and {{./}} operators are available if entry-wise multiplication or division is desired.
Floats are by default double precision; single precision can be specified with the //single// constructor. MATLAB has convenient matrix literal notation: commas or spaces can be used to separate row entries, and semicolons or newlines can be used to separate rows.
Arrays and vectors are implemented as single-row ({{1xn}}) matrices. As a result an //n//-element vector must be transposed before it can be multiplied on the right of a {{mxn}} matrix.
Numeric literals that lack a decimal point such as //17// and //-34// create floats, in contrast to most other programming languages. To create an integer, an integer constructor which specifies the size such as //int8// and //uint16// must be used. Matrices of integers are supported, but the entries in a given matrix must all have the same numeric type.
Strings are implemented as single-row ({{1xn}}) matrices of characters. Matrices cannot contain strings. If a string is put in matrix literal, each character in the string becomes an entry in the resulting matrix. This is consistent with how matrices are treated if they are nested inside another matrix. The following literals all yield the same string or {{1xn}} matrix of characters:
code ‘foo’ [ ‘f’ ‘o’ ‘o’ ] [ ‘foo’ ] [ [ ‘f’ ‘o’ ‘o’ ] ] /code
//true// and //false// are functions which return matrices of ones and zeros. The ones and zeros have type //logical// instead of //double//, which is created by the literals 1 and 0. Other than having a different class, the 0 and 1 of type //logical// behave the same as the 0 and 1 of type //double//.
MATLAB has a tuple type (in MATLAB terminology, a cell array) which can be used to hold multiple strings. It can also hold values with different types.
# r + [#top R]
[http://cran.r-project.org/doc/manuals/R-intro.html An Introduction to R] [http://adv-r.had.co.nz/ Advanced R Programming] [http://cran.r-project.org/ The Comprehensive R Archive Network]
The primitive data types of R are vectors of floats, vectors of strings, and vectors of booleans. There is no distinction between a scalar and a vector with one entry in it. Functions and operators which accept a scalar argument will typically accept a vector argument, returning a vector of the same size with the scalar operation performed on each the entries of the original vector.
The scalars in a vector must all be of the same type, but R also provides a //list// data type which can be used as a tuple (entries accessed by index), record (entries accessed by name), or even as a dictionary.
In addition R provides a //data frame// type which is a list (in R terminology) of vectors all of the same length. Data frames are equivalent to the data sets of other statistical analysis packages.
# numpy + [#top NumPy]
[http://docs.scipy.org/doc/ NumPy and SciPy Documentation] [http://matplotlib.sourceforge.net/ matplotlib intro] [http://www.scipy.org/NumPy_for_Matlab_Users NumPy for Matlab Users] [http://pandas.pydata.org/pandas-docs/stable/ Pandas Documentation] [http://pandas.pydata.org/pandas-docs/dev/genindex.html Pandas Method/Attribute Index]
NumPy is a Python library which provides a data type called {{array}}. It differs from the Python {{list}} data type in the following ways:
- N-dimensional. Although the {{list}} type can be nested to hold higher dimension data, the {{array}} can hold higher dimension data in a space efficient manner without using indirection.
- homogeneous. The elements of an {{array}} are restricted to be of a specified type. The NumPy library introduces new primitive types not available in vanilla Python. However, the element type of an array can be {{object}} which permits storing anything in the array.
In the reference sheet the [#array array section] covers the vanilla Python {{list}} and the [#multidimensional-array multidimensional array section] covers the NumPy {{array}}.
//List the NumPy primitive types//
SciPy, Matplotlib, and Pandas are libraries which depend on Numpy.
# julia + [#top Julia]