Path: octave.ipynb
Views: 789
Image: ubuntu2004-dev
Project: Software 20.04
In [1]:
version()

Out[1]:
ans = 6.3.0 
In [5]:
function sqs = squares(n)
# Compute the squares of the numbers from 1 to n.

### BEGIN SOLUTION
# Put correct code here. This code is removed for the student version, but is
# used to confirm that your tests are valid.
if (n <= 0)
error("n must be positive")
endif
sqs = (1:n).^2;
### END SOLUTION
endfunction

In [6]:
# [Modify the tests below for your own problem]
# Check that squares returns the correct output for several inputs:
assert(squares(1), [1])
assert(squares(2), [1 4])

# Check that squares raises an error for invalid input:
number_of_errors = 0;
for n = [0 -1]
try
squares(n);
catch
number_of_errors++;
end_try_catch
endfor
assert(number_of_errors, 2)

### BEGIN HIDDEN TESTS
# students will NOT see these extra tests
assert(squares(10), [1 4 9 16 25 36 49 64 81 100])
### END HIDDEN TESTS

In [7]:
function s = foo(a, b)
# Compute the sum of a and b.

### BEGIN SOLUTION
s = a + b;
### END SOLUTION
endfunction

In [8]:
foo(23,23)

Out[8]:
ans = 46 
In [9]:
[2 3 4]' * [4 3 -1]

Out[9]:
ans = 8 6 -2 12 9 -3 16 12 -4 
In [10]:
x = rand(3,3)^3

Out[10]:
x = 2.1431 1.7423 3.0724 2.0164 1.5665 2.8237 2.0113 1.6347 2.7902 
In [8]:
save r-octave.mat x -7

In [9]:
scatter(sort(rand(1000, 1)), sort(randn(1000, 1)))

Out[9]:
In [10]:
i = 0:.1:2*pi;
plot(i, sin(i))

Out[10]:
In [11]:
pkg load symbolic;
syms x;
f = sin(x);
diff(f,x)

Out[11]:
Symbolic pkg v2.9.0: /usr/local/lib/python3.8/dist-packages/sympy/__init__.py:672: SymPyDeprecationWarning: importing sympy.core.compatibility with 'from sympy import *' has been deprecated since SymPy 1.6. Use import sympy.core.compatibility instead. See https://github.com/sympy/sympy/issues/18245 for more info. self.Warn( Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 12, in octoutput_drv File "<stdin>", line 54, in octoutput File "<stdin>", line 55, in octoutput File "/usr/local/lib/python3.8/dist-packages/sympy/__init__.py", line 677, in __getattr__ return getattr(self.mod, name) AttributeError: module 'sympy.core.compatibility' has no attribute 'integer_types' Waiting...............warning: readblock: timeout of 30 exceeded, breaking out warning: called from readblock at line 101 column 7 python_ipc_popen2 at line 99 column 16 python_ipc_driver at line 62 column 15 pycall_sympy__ at line 163 column 11 valid_sym_assumptions at line 38 column 10 assumptions at line 82 column 7 syms at line 97 column 13 no output so far error: ipc_popen2: something wrong? timed out starting python error: called from python_ipc_popen2 at line 101 column 7 python_ipc_driver at line 62 column 15 pycall_sympy__ at line 163 column 11 valid_sym_assumptions at line 38 column 10 assumptions at line 82 column 7 syms at line 97 column 13 error: diff: order K must be a scalar or [] 
In [12]:
pkg load symbolic; syms x
f = 2 * (cos(x) + sin(x)^2)
f1 = diff(f, x)

Out[12]:
/usr/local/lib/python3.8/dist-packages/sympy/__init__.py:672: SymPyDeprecationWarning: importing sympy.core.compatibility with 'from sympy import *' has been deprecated since SymPy 1.6. Use import sympy.core.compatibility instead. See https://github.com/sympy/sympy/issues/18245 for more info. self.Warn( Traceback (most recent call last): File "<stdin>", line 4, in <module> File "<stdin>", line 12, in octoutput_drv File "<stdin>", line 55, in octoutput File "/usr/local/lib/python3.8/dist-packages/sympy/__init__.py", line 677, in __getattr__ return getattr(self.mod, name) AttributeError: module 'sympy.core.compatibility' has no attribute 'integer_types' error: Python exception: AttributeError: module 'sympy.core.compatibility' has no attribute 'integer_types' occurred while copying variables to Python. Try "sympref reset" and repeat your command? (consider filing an issue at https://github.com/cbm755/octsympy/issues) error: called from pycall_sympy__ at line 191 column 5 valid_sym_assumptions at line 38 column 10 assumptions at line 82 column 7 syms at line 97 column 13 f = 3.0540 2.6676 2.9295 3.7069 3.1595 3.4936 3.1302 2.7675 3.0067 error: diff: order K must be a scalar or [] 
In [13]:
xx = -10:0.1:10;
plot(xx, f(xx))

Out[13]:
warning: non-integer range used as index error: f(-10): subscripts must be either integers 1 to (2^63)-1 or logicals
In [14]:
pkg load image

In [15]:
a = ones(100, 100);
b = ones(100, 100);
b(3, 1) = .5;
psnr(a, b)

Out[15]:
ans = 46.021

This plot shows the famous 3D sombrero.

A quadratic meshgrid of $x$ and $y$ coordinates is evaluated via $\sqrt{x^2 + y^2} + \epsilon$ and the value $r$ is then the value plotted along the third dimension.

Reference: 3d plots

In [11]:
tx = ty = linspace (-8, 8, 41)';
[xx, yy] = meshgrid (tx, ty);
r = sqrt (xx .^ 2 + yy .^ 2) + eps;
tz = sin (r) ./ r;
mesh (tx, ty, tz);
xlabel ("tx");
ylabel ("ty");
zlabel ("tz");
title ("3-D Sombrero plot");

Out[11]:
In [12]:
[x,y] = meshgrid(-16:0.5:16);
r = hypot(x,y)/2 + eps;
figure;
surf(sin(r)./r);
colormap(jet);

Out[12]:
In [0]:



This draws the set of points, where the given equation is satisfied. Here, it shows a tilted ellipse.

$x^2 + 3 (y-1)^2 + \frac{x y}{2} = 6$

Reference: ezplot

In [13]:
ezplot (@(x, y) x.^2 + 3 * (y - 1).^2 + .5 * x .* y - 6)

Out[13]:

Imagine you want to evaluate a binary function $f(x,\,y) := x + 2 y$.

For evaluating it in vectorized notation, you need a grid for the cartesian product of all $x$ and $y$.

In [14]:
x = 0:3;
y = 0:4;
[xx, yy] = meshgrid(x, y);
xx + 2*yy

Out[14]:
ans = 0 1 2 3 2 3 4 5 4 5 6 7 6 7 8 9 8 9 10 11 

## dsolve and sympy in symbolic

In [22]:
pkg load symbolic
syms y(x)
de = diff(y) == x;
f = dsolve(de, y(1) == 1)

Out[22]:
Traceback (most recent call last): File "<stdin>", line 4, in <module> File "<stdin>", line 12, in octoutput_drv File "<stdin>", line 55, in octoutput File "/usr/local/lib/python3.8/dist-packages/sympy/__init__.py", line 677, in __getattr__ return getattr(self.mod, name) AttributeError: module 'sympy.core.compatibility' has no attribute 'integer_types' error: Python exception: AttributeError: module 'sympy.core.compatibility' has no attribute 'integer_types' occurred while copying variables to Python. Try "sympref reset" and repeat your command? (consider filing an issue at https://github.com/cbm755/octsympy/issues) error: called from pycall_sympy__ at line 191 column 5 valid_sym_assumptions at line 38 column 10 assumptions at line 82 column 7 syms at line 97 column 13 error: 'dsolve' undefined near line 1, column 1 'dsolve' is a method of class 'sym'; it must be called with a 'sym' argument (see 'help @sym/dsolve'). Please read <https://www.octave.org/missing.html> to learn how you can contribute missing functionality.

## Octave's ODE PKG in Action

In [23]:
pkg load odepkg;

In [24]:
dxdt = @(t, x) - 0.24 * x.^2 + t;
tsteps = [0:0.1:5];
[t, x] = ode45(dxdt, tsteps, [-1:0.5:3]);
plot(t, x)

Out[24]:
In [0]:


In [0]:



You can run numerical optimizations via the optim package.

In this example we minimize the classical Rosenbrock function in 20 dimensions using BFGS.

In [25]:
pkg load optim;

function [obj_value, gradient] = objective(theta, location)
x = theta - location + ones(rows(theta),1); # move minimizer to "location"
endfunction

dim = 20;                 # dimension of Rosenbrock function
theta0 = zeros(dim+1,1);  # starting values
location = (0:dim)/dim;   # true values
location = location';
control = {Inf,1};        # maxiters, verbosity

bfgsmin("objective", {theta0, location}, control);

Out[25]:
Picked up _JAVA_OPTIONS: -Djava.io.tmpdir=/home/user/tmp -Xms64m ------------------------------------------------ bfgsmin final results: 65 iterations function value: 2.17563e-16 STRONG CONVERGENCE Function conv 1 Param conv 1 Gradient conv 1 used numeric gradient param gradient (n) change 0.00000 0.00000 -0.00000 0.05000 -0.00000 0.00000 0.10000 0.00000 0.00000 0.15000 -0.00000 0.00000 0.20000 -0.00000 0.00000 0.25000 0.00000 0.00000 0.30000 -0.00000 0.00000 0.35000 -0.00000 0.00000 0.40000 -0.00000 0.00000 0.45000 0.00000 -0.00000 0.50000 0.00000 -0.00000 0.55000 -0.00000 0.00000 0.60000 0.00000 -0.00000 0.65000 0.00000 -0.00000 0.70000 -0.00000 0.00000 0.75000 -0.00000 0.00000 0.80000 0.00000 0.00000 0.85000 0.00000 0.00000 0.90000 0.00000 0.00000 0.95000 -0.00000 0.00000 1.00000 0.00000 0.00000

## testing java support

In [19]:
__have_feature__ JAVA

Out[19]:
ans = 1
In [20]:
javaclasspath

Out[20]:
Picked up _JAVA_OPTIONS: -Djava.io.tmpdir=/home/user/tmp -Xms64m STATIC JAVA PATH - empty - DYNAMIC JAVA PATH - empty -
In [4]:
a = 1.001;
b = javaObject ("java.math.BigDecimal", a);

In [5]:
isjava (b)
b.toString()

Out[5]:
ans = 1 ans = 1.000999999999999889865875957184471189975738525390625
In [6]:
b.add(b).toString()

Out[6]:
ans = 2.001999999999999779731751914368942379951477050781250
In [10]:
[3 4 5]

Out[10]:
ans = 3 4 5
In [3]:
randn(5)

Out[3]:
ans = 0.1526 -1.7668 0.8292 1.4689 1.4122 1.0429 -0.6826 -0.3058 -0.5276 -1.6222 1.8058 0.5720 0.6472 -0.9762 0.1591 0.3325 -0.5342 1.1739 1.2969 0.1275 0.1976 0.5135 1.3049 1.6371 -0.3589
In [2]:
javaObject('java.math.BigInteger','0')

Out[2]:
Picked up _JAVA_OPTIONS: -Djava.io.tmpdir=/home/user/tmp -Xms64m ans = <Java object: java.math.BigInteger>
In [8]:
randn(6,6) \ randn(6,1)

Out[8]:
Restarting kernel... Done!
[Errno 9] Bad file descriptor 
In [4]:
randn(6,6)

Out[4]:
ans = -0.927292 0.297279 0.564452 0.020172 0.571244 0.529164 -1.139541 -0.286720 0.465265 -0.071164 0.032360 -0.867946 0.798668 -1.469038 0.255304 -1.145126 1.428896 -0.877692 1.945952 0.602504 -2.536855 0.754410 0.857399 -0.470719 1.034842 -0.297812 0.019681 -1.011211 0.383840 0.458903 0.172154 -0.753179 0.925745 0.750128 -0.210879 0.166060
In [7]:
41 \ 4

Out[7]:
ans = 0.097561
In [0]: