uploaded all materials
This commit is contained in:
24
lessons/lesson04/BasicClass.m
Normal file
24
lessons/lesson04/BasicClass.m
Normal file
@ -0,0 +1,24 @@
|
||||
classdef BasicClass
|
||||
% BasicClass is a simple sample class definition
|
||||
properties (Access = private)
|
||||
vals % vector
|
||||
end
|
||||
|
||||
methods
|
||||
function obj = BasicClass(x)
|
||||
% Construct an instance of this class
|
||||
% Sets x to the object's vals property
|
||||
obj.vals = x;
|
||||
end
|
||||
|
||||
function z = getVals(obj)
|
||||
z = obj.vals;
|
||||
end
|
||||
|
||||
function z = findClosest(obj,n)
|
||||
% Find closest entry in obj.vals to n
|
||||
[~, ind] = min(abs(obj.vals - n));
|
||||
z = obj.vals(ind);
|
||||
end
|
||||
end
|
||||
end
|
57
lessons/lesson04/controlflow.m
Normal file
57
lessons/lesson04/controlflow.m
Normal file
@ -0,0 +1,57 @@
|
||||
%% Lesson 4b: Control Sequences
|
||||
%
|
||||
% Since it likes to play at being a general purpose programming language,
|
||||
% MATLAB has control flow constructs (if, loops, etc.). Sometimes not
|
||||
% everything is achievable with a linear set of instructions and vectorization,
|
||||
% such as in particularly complex situations.
|
||||
|
||||
clear; clc; close all;
|
||||
|
||||
%% For loops (a review)
|
||||
total=0;
|
||||
for i=1:10
|
||||
total = total + i;
|
||||
end
|
||||
total
|
||||
|
||||
%% If...Else Statements
|
||||
gpa = 2.3;
|
||||
if gpa < 2
|
||||
fprintf('You are in DANGER!!!\n')
|
||||
elseif gpa >= 2 && gpa < 3.5
|
||||
fprintf('You are safe.\n')
|
||||
elseif gpa >= 3.5 && gpa < 3.7
|
||||
fprintf('Cum Laude\n')
|
||||
elseif gpa >= 3.7 && gpa < 3.8
|
||||
fprintf('Magna Cum Laude\n')
|
||||
elseif gpa >= 3.8 && gpa < 4
|
||||
fprintf('Summa Cum Laude\n')
|
||||
else
|
||||
fprintf("invalid gpa\n")
|
||||
end
|
||||
|
||||
%% While loop
|
||||
% Iterate while a condition is true, as opposed to iterating over a vector.
|
||||
total = 0;
|
||||
i = 0;
|
||||
while i <= 10
|
||||
total = total + i;
|
||||
i = i+1;
|
||||
end
|
||||
total
|
||||
|
||||
%% Try/catch blocks
|
||||
% Try and catch allow for error handling, which can be useful when using
|
||||
% user-supplied input that may be invalid. See the documentation of any
|
||||
% function to see what errors it may throw.
|
||||
%
|
||||
% It is also a good idea for you to validate input if writing a function
|
||||
% intended to be used by other people. This is very common in all MATLAB
|
||||
% builtin/toolbox functions.
|
||||
try
|
||||
a = [1 2; 3 4];
|
||||
b = [1 2 3 4];
|
||||
c = a*b % can't do this! not the right dimensions!
|
||||
catch err
|
||||
fprintf('Hey! Not allowed!\n');
|
||||
end
|
162
lessons/lesson04/datatypes.m
Normal file
162
lessons/lesson04/datatypes.m
Normal file
@ -0,0 +1,162 @@
|
||||
%% Lesson 5b: Datatypes
|
||||
% There are several basic data types in MATLAB:
|
||||
%
|
||||
% - single, double (floating pt. 32 and 64 bit respectively)
|
||||
% - int8, int16, int32, int64 (different size integers)
|
||||
% - uint8, uint16, uint32, uint64 (different size unsigned intergers)
|
||||
% - logicals
|
||||
% - char arrays, strings
|
||||
% - cell arrays
|
||||
clc; clear; close all;
|
||||
|
||||
%% What type is this?
|
||||
% You can get the data type of a variable using the class function. Most
|
||||
% of the time, values default to fp64, which is often good for
|
||||
% scientific computing with high accuracy.
|
||||
a = 10;
|
||||
class(a);
|
||||
|
||||
b = int8(a);
|
||||
class(b);
|
||||
|
||||
%% Data Type Sizes
|
||||
% Different data types take up different amounts of space in your memory
|
||||
% and hard drive. Let's take a look at some standard sizes in MATLAB.
|
||||
A = randn(1, 'double');
|
||||
B = randn(1, 'single');
|
||||
C = true(1);
|
||||
D = 'D';
|
||||
|
||||
% lists info of the variables in the current workspace
|
||||
whos;
|
||||
|
||||
% If your data is getting too large, it can help to cast to smaller types.
|
||||
% `single` is a smaller fp type, and uint8/uint16 are smaller
|
||||
|
||||
%% Different Interpretations
|
||||
% Be careful with what data types you feed into built in functions.
|
||||
% MATLAB will have different responses to different types.
|
||||
|
||||
% imshow with ints
|
||||
imshow(uint8(rand(128, 128, 3)));
|
||||
|
||||
%%
|
||||
% imshow with doubles
|
||||
imshow(double(rand(128, 128, 3)));
|
||||
|
||||
%% Overflow and Underflow
|
||||
% With floating point, we are trying to represent real numbers. Obviously
|
||||
% there must be some spacing between representable numbers using a
|
||||
% fixed-size representation. Let's take a look.
|
||||
%
|
||||
% eps() shows the error between a number and its true value given IEEE
|
||||
% floating-point.
|
||||
L = logspace(-400, 400, 4096);
|
||||
loglog(L, eps(L), single(L), eps(single(L)));
|
||||
|
||||
% As the plot shows, doubles have a much larger range as well as higher
|
||||
% precision at each point. Let's see how this applies in practice.
|
||||
|
||||
%% More examples examples of eps
|
||||
eps(1);
|
||||
(1 + 0.5001*eps(1)) - 1;
|
||||
(1 + 0.4999*eps(1)) - 1;
|
||||
|
||||
eps(1e16);
|
||||
1 + 1e16 == 1e16;
|
||||
|
||||
%% More examples of overflow/underflow
|
||||
single(10^50);
|
||||
single(10^-50);
|
||||
|
||||
uint8(256);
|
||||
int8(-129);
|
||||
|
||||
%% Cell Arrays
|
||||
% Matrices can only store values of the same type (homogenous data).
|
||||
% Cell arrays can store heterogeneous (but still rectangular) data.
|
||||
% However, they are relatively slow and should be used sparingly.
|
||||
courses = {
|
||||
'', 'Modern Physics', 'Signals and Systems', ...
|
||||
'Complex Analysis', 'Drawing and Sketching for Engineers'; ...
|
||||
|
||||
'Grades', 70 + 3*randn(132,1), 80 + 3*randn(41,1), ...
|
||||
40 + 3*randn(20,1), 100*ones(29,1); ...
|
||||
|
||||
'Teachers', {'Debroy'; 'Yecko'}, {'Fontaine'}, {'Smyth'}, {'Dell'}
|
||||
};
|
||||
|
||||
%% Difference between {} and ()
|
||||
% As we've seen before, () performs matrix indexing. A cell array behaves
|
||||
% as a matrix of cell-arrays; indexing it using () will also produce a cell
|
||||
% array.
|
||||
%
|
||||
% {} performs matrix indexing, and also extracts the values of the cell(s).
|
||||
% Usually, this is what you want when immediately indexing a cell array.
|
||||
%
|
||||
% Confusingly (or not?) you can double-index cell arrays using `{}`, but
|
||||
% you cannot double-index matrices using `()`.
|
||||
courses(1,2);
|
||||
courses{1,2};
|
||||
courses{2,2}(3:5,1);
|
||||
courses(3,2);
|
||||
courses{3,2};
|
||||
courses{3,2}{1}(1);
|
||||
|
||||
%% Objects and Classes
|
||||
% MATLAB supports OOP programming. We saw a basic class definition last
|
||||
% class. Classes are also used in all of MATLAB's toolboxes (e.g., ML,
|
||||
% signal processing).
|
||||
x = randn(10000, 1);
|
||||
h = histogram(x); % h is a histogram class
|
||||
|
||||
properties(h);
|
||||
methods(h);
|
||||
|
||||
% Check out the documentation for more info on the histogram class and
|
||||
% other classes.
|
||||
|
||||
%% Structs and Objects
|
||||
% MATLAB also supports `struct`s. Structs are like objects in that they
|
||||
% can combine multiple values under the same variable (composite data),
|
||||
% and use the same dot-indexing syntax. However, they are not defined by
|
||||
% and constructed using a class, but rather using the `struct` constructor.
|
||||
|
||||
sfield1 = 'a'; svalue1 = 5;
|
||||
sfield2 = 'b'; svalue2 = [3 6];
|
||||
sfield3 = 'c'; svalue3 = "Hello World";
|
||||
sfield4 = 'd'; svalue4 = {'cell array'};
|
||||
|
||||
s = struct( ...
|
||||
sfield1, svalue1, ...
|
||||
sfield2, svalue2, ...
|
||||
sfield3, svalue3, ...
|
||||
sfield4, svalue4 ...
|
||||
);
|
||||
|
||||
s.a;
|
||||
s.b(2);
|
||||
|
||||
%% Struct with cell array fields
|
||||
% Cell arrays as struct fields may be used to generate an array of structs.
|
||||
tfield1 = 'f1'; tvalue1 = zeros(1,10);
|
||||
tfield2 = 'f2'; tvalue2 = {'a', 'b'};
|
||||
tfield3 = 'f3'; tvalue3 = {pi, pi.^2};
|
||||
tfield4 = 'f4'; tvalue4 = {'fourth'};
|
||||
t = struct( ...
|
||||
tfield1, tvalue1, ...
|
||||
tfield2, tvalue2, ...
|
||||
tfield3, tvalue3, ...
|
||||
tfield4, tvalue4 ...
|
||||
);
|
||||
|
||||
t(1);
|
||||
t(2);
|
||||
|
||||
%% Adding fields to a struct
|
||||
% Struct fields are not fixed; you can add fields to it after it is
|
||||
% constructed using dot-indexing.
|
||||
u = struct;
|
||||
u.a = [1 3 5 7];
|
||||
u.b = ["Hello","World!"];
|
||||
u;
|
19
lessons/lesson04/distance.m
Normal file
19
lessons/lesson04/distance.m
Normal file
@ -0,0 +1,19 @@
|
||||
% In a file like this one (which only defines normal functions, and in which
|
||||
% the first function is hononymous with the filename), the first function is a
|
||||
% public function, and all other functions are local helper functions.
|
||||
%
|
||||
% Note that you DO NOT want to put clc; clear; close all; at the top of a file
|
||||
% like this; it only makes sense to do this at the top of script files when you
|
||||
% want to clean your workspace!
|
||||
|
||||
% Calculate Euclidean distance
|
||||
% A public function, callable by other files and from the Command Window if
|
||||
% this is in the MATLAB path.
|
||||
function d = distance(x, y)
|
||||
d = sqrt(sq(x) + sq(y));
|
||||
end
|
||||
|
||||
% A local helper function. Only accessible within this file.
|
||||
function x = sq(x)
|
||||
x = x * x;
|
||||
end
|
34
lessons/lesson04/for_loops.m
Normal file
34
lessons/lesson04/for_loops.m
Normal file
@ -0,0 +1,34 @@
|
||||
%% Lesson 2b: Control Sequence - For loops
|
||||
% Similar to other languages, MATLAB have if, while and for control
|
||||
% sequences. For loops are one of the commonly used control sequences in
|
||||
% MATLAB. We will continue the discussion of if and while in the next
|
||||
% lesson.
|
||||
|
||||
clear;
|
||||
n = 1e7;
|
||||
% D = zeros(1,n); % This is called pre-allocation
|
||||
% try uncommenting this line to see the
|
||||
% difference. Memory allocations are slow!
|
||||
|
||||
% Calculate fib(n). Hard to do vectorized unless we know Binet's formula.
|
||||
% (Note that this will quickly overflow, but that's not our objective
|
||||
% here.)
|
||||
D(1) = 1;
|
||||
D(2) = 2;
|
||||
tic % start timer
|
||||
for i = 3:n
|
||||
D(i) = D(i-1) + D(i-2);
|
||||
end
|
||||
toc % print elapsed time since last tic
|
||||
|
||||
%% Be careful!
|
||||
% For loops are considered the more inefficient type of operation in
|
||||
% MATLAB. Performing operations on vectors is faster because your hardware
|
||||
% can optimize vectorized instructions, and because the "for" construct
|
||||
% exists in MATLAB's runtime, which is essentially a scripting language and
|
||||
% thus is slow.
|
||||
%
|
||||
% However, things are changing, and things like parfor (parallel-for) and
|
||||
% advanced JIT (just-in-time) compilation are improving the performance of
|
||||
% loops. But vectorized operations are almost always faster and should
|
||||
% be used where possible.
|
177
lessons/lesson04/funnnnnn.m
Normal file
177
lessons/lesson04/funnnnnn.m
Normal file
@ -0,0 +1,177 @@
|
||||
%% Lesson 4a: Functions
|
||||
%
|
||||
% Objectives:
|
||||
% - Explore MATLAB's function-calling syntax and semantics.
|
||||
% - Explore anonymous functions.
|
||||
% - Explore local functions.
|
||||
% - Explore regular functions.
|
||||
clear; clc; close all;
|
||||
|
||||
%% Functions
|
||||
% Functions in any programming language are the means of abstraction. In
|
||||
% functional programming, they are a fundamental structure with the power to
|
||||
% build any complex form. In imperative and scientific computing, functions are
|
||||
% useful to prevent code duplication and improve maintainability.
|
||||
%
|
||||
% There are a few varieties of MATLAB, each of which has very different syntax
|
||||
% and semantics, so buckle up!
|
||||
%
|
||||
% (Insider information from MathWorks: MATLAB is working on improving the
|
||||
% support/accesibility of functional programming! So there may be some
|
||||
% improvements in the near future!)
|
||||
%
|
||||
% Note: this lecture was heavily modified by a functional-programming fan!
|
||||
|
||||
%% Using functions
|
||||
% All functions are called (invoked) in the same manner: by using the
|
||||
% function's name followed by the list of parameters with which to invoke the
|
||||
% function.
|
||||
z = zeros(1, 3);
|
||||
mean([1, 2, 3, 4, 5]);
|
||||
|
||||
% Functions may have optional parameters, and they may behave differently when
|
||||
% called with different inputs (polymorphism) or when different numbers of
|
||||
% outputs are expected. They may also return zero, one, or multiple values.
|
||||
size1 = size(z);
|
||||
size2 = size(z, 2); % optional second parameter
|
||||
|
||||
hist(1:10); % displays a historgram
|
||||
a = hist(1:10); % stores a histogram into the variable a, and does
|
||||
% not display a histogram
|
||||
|
||||
[r1, r2] = HelloWorld("Jon", "Lam"); % Function returning multiple
|
||||
% values (HelloWorld defined later in
|
||||
% file)
|
||||
|
||||
% There is a second way that you've seen to call functions, called "command
|
||||
% syntax." These are translatable to the regular function syntax. Any textual
|
||||
% arguments in this syntax will be interpreted as strings, which is similar to
|
||||
% UNIX sh commands arguments (hence "command" syntax).
|
||||
clear a b; % clear("a", "b")
|
||||
close all; % close("all")
|
||||
mkdir test; % mkdir("test")
|
||||
rmdir test; % rmdir("test")
|
||||
|
||||
% Note that if a function takes no arguments, the parentheses may also be
|
||||
% omitted. (This is not true for anonymous functions, as we will see.)
|
||||
clc; % clc()
|
||||
figure; % figure()
|
||||
|
||||
%% Anonymous functions
|
||||
% Anonymous functions are defined with the following syntax:
|
||||
%
|
||||
% @(arg1, arg2, ...) fun_body
|
||||
%
|
||||
% These allow us to conveniently define functions inline, and perform some
|
||||
% functional programming capabilities. In other programming languages, they may
|
||||
% be known as "arrow functions" or "lambda functions."
|
||||
cube = @(x) x.^3;
|
||||
parabaloid = @(x, y) x.^2 + y.^2;
|
||||
|
||||
% Call these functions like any other function.
|
||||
cube(3);
|
||||
parabaloid(3, 4);
|
||||
|
||||
% As the name suggests, anonymous functions don't have to be assigned names; by
|
||||
% themselves, they are "function values" or "function expressions" and can be
|
||||
% handled like any other expression. (I.e., "first-class" functions). Usually,
|
||||
% we assign it to a variable to name it, just as we do for most useful
|
||||
% expressions.
|
||||
@(x) x.^3;
|
||||
cube_fnval = ans;
|
||||
|
||||
% Anonymous functions can capture variables from the surrounding scope. They
|
||||
% may exist anywhere an expression may exist (e.g., within the body of another
|
||||
% function).
|
||||
outside_variable = 3;
|
||||
capture_fn = @() outside_variable;
|
||||
outside_variable = 4;
|
||||
|
||||
capture_fn; % What will this return?
|
||||
capture_fn(); % What will this return?
|
||||
|
||||
% Lexical scoping and closures apply! This allows for some degree of functional
|
||||
% programming (e.g., function currying).
|
||||
curried_sum = @(x) @(y) x + y;
|
||||
add_two = curried_sum(2);
|
||||
add_two(5); % The binding x <- 2 is captured in
|
||||
% add_two's lexical closure
|
||||
|
||||
% add_two(2)(5) % Can't do this due to MATLAB's syntax,
|
||||
% just like how you can't double-index
|
||||
% an expression
|
||||
|
||||
%% Example: Higher-order functions
|
||||
% An example of passing functions around like any other variable. (Functions
|
||||
% that accept other functions as parameters or return a function are called
|
||||
% "higher-order functions.")
|
||||
%
|
||||
% In this example, compose is the function composition operator. compose(f,g)
|
||||
% = (f o g). It is a HOF because it takes two functions as parameters, and it
|
||||
% returns a function.
|
||||
compose = @(f, g) @(x) f(g(x));
|
||||
add_three = @(x) x + 3;
|
||||
times_four = @(x) x * 4;
|
||||
x_times_four_plus_three = compose(add_three, times_four);
|
||||
|
||||
x = 0:10;
|
||||
y = x_times_four_plus_three(x);
|
||||
plot(x, y);
|
||||
grid on;
|
||||
|
||||
%% Normal Functions
|
||||
% "Normal functions" (so-called because they were the first type of function in
|
||||
% MATLAB) are defined using the syntax shown below, and are invoked in the same
|
||||
% way as anonymous functions.
|
||||
%
|
||||
% Note that normal functions cannot be passed around as variables, and this
|
||||
% makes a functional-programming style impossible using normal functions.
|
||||
%
|
||||
% Unlike anonymous functions, normal functions may include multiple statements,
|
||||
% may return multiple values, are invoked if appearing in an expression without
|
||||
% parentheses (unless you use a function handle), and do not capture variables
|
||||
% from the surrounding scope/workspace.
|
||||
%
|
||||
% There are two types of normal functions: "public" normal functions, which
|
||||
% must be placed at the beginning of a *.m file with the same name as the
|
||||
% function, or local/private normal functions, which may appear at the end of a
|
||||
% *.m file (after anything that is not a function). Both types of normal
|
||||
% functions must appear after any statements in the file; in other words, a
|
||||
% file defining a non-local function can only contain a list of function
|
||||
% definitions, the first of is public and the rest of which are private. As the
|
||||
% name suggests, local functions are only in scope in the file in which they
|
||||
% are defined, whereas public functions may be accessible if they are on the
|
||||
% MATLAB path.
|
||||
%
|
||||
% You don't need to understand all this right now; this brief explanation and
|
||||
% the MATLAB documentation can serve as a reference for your future MATLAB
|
||||
% endeavors.
|
||||
|
||||
%% The MATLAB Path
|
||||
% In order to call a public function defined in another file, the function file
|
||||
% must be in the current folder or on the MATLAB path.
|
||||
matlabpath; % Print out MATLAB path
|
||||
|
||||
%% Invoking regular functions
|
||||
% Note that this section is before the local function definition because the
|
||||
% local function must be defined after all statements in the script.
|
||||
%
|
||||
% eye() is a builtin function. Here we call it with no arguments, so the first
|
||||
% argument's value defaults to 1. distance() is a public function defined in
|
||||
% the file distance.m HelloWorld() is a local function defined below
|
||||
eye;
|
||||
distance(3, 4);
|
||||
HelloWorld("Jon", "Lam"); % Invoking HelloWorld and ignoring outputs
|
||||
|
||||
%% Defining a local function
|
||||
function [res1, res2] = HelloWorld(name1, name2)
|
||||
fprintf("Hello, world! %s %s\n", name1, name2);
|
||||
res1 = 3;
|
||||
res2 = [5 6];
|
||||
end
|
||||
|
||||
%% Other fun stuff:
|
||||
% Function handles
|
||||
% `feval` on function handles and strings
|
||||
% Double-indexing using functions
|
||||
% Viewing source code using `edit`
|
572
lessons/lesson04/octave-log.txt
Normal file
572
lessons/lesson04/octave-log.txt
Normal file
@ -0,0 +1,572 @@
|
||||
octave:2> z = zeros(3)
|
||||
z =
|
||||
|
||||
0 0 0
|
||||
0 0 0
|
||||
0 0 0
|
||||
|
||||
octave:3> mean(1:5)
|
||||
ans = 3
|
||||
octave:4> zeros(3)
|
||||
ans =
|
||||
|
||||
0 0 0
|
||||
0 0 0
|
||||
0 0 0
|
||||
|
||||
octave:5> zeros(3, 1)
|
||||
ans =
|
||||
|
||||
0
|
||||
0
|
||||
0
|
||||
|
||||
octave:6> help sum
|
||||
'sum' is a built-in function from the file libinterp/corefcn/data.cc
|
||||
|
||||
-- sum (X)
|
||||
-- sum (X, DIM)
|
||||
-- sum (..., "native")
|
||||
-- sum (..., "double")
|
||||
-- sum (..., "extra")
|
||||
Sum of elements along dimension DIM.
|
||||
|
||||
If DIM is omitted, it defaults to the first non-singleton
|
||||
dimension.
|
||||
|
||||
The optional "type" input determines the class of the variable used
|
||||
for calculations. By default, operations on floating point inputs
|
||||
(double or single) are performed in their native data type, while
|
||||
operations on integer, logical, and character data types are
|
||||
performed using doubles. If the argument "native" is given, then
|
||||
the operation is performed in the same type as the original
|
||||
argument.
|
||||
|
||||
For example:
|
||||
|
||||
sum ([true, true])
|
||||
=> 2
|
||||
sum ([true, true], "native")
|
||||
=> true
|
||||
|
||||
If "double" is given the sum is performed in double precision even
|
||||
for single precision inputs.
|
||||
|
||||
For double precision inputs, the "extra" option will use a more
|
||||
accurate algorithm than straightforward summation. For single
|
||||
precision inputs, "extra" is the same as "double". For all other
|
||||
data type "extra" has no effect.
|
||||
|
||||
See also: cumsum, sumsq, prod.
|
||||
|
||||
Additional help for built-in functions and operators is
|
||||
available in the online version of the manual. Use the command
|
||||
'doc <topic>' to search the manual index.
|
||||
|
||||
Help and information about Octave is also available on the WWW
|
||||
at https://www.octave.org and via the help@octave.org
|
||||
mailing list.
|
||||
octave:7> sum(eye(3))
|
||||
ans =
|
||||
|
||||
1 1 1
|
||||
|
||||
octave:8> eye(3)
|
||||
ans =
|
||||
|
||||
Diagonal Matrix
|
||||
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
octave:9> sum(eye(3))
|
||||
ans =
|
||||
|
||||
1 1 1
|
||||
|
||||
octave:10> sum(eye(3), 2)
|
||||
ans =
|
||||
|
||||
1
|
||||
1
|
||||
1
|
||||
|
||||
octave:11> sum(eye(3), 3)
|
||||
ans =
|
||||
|
||||
1 0 0
|
||||
0 1 0
|
||||
0 0 1
|
||||
|
||||
octave:12> hold on
|
||||
octave:13> close all
|
||||
octave:14> close("all")
|
||||
octave:15> hold("on")
|
||||
octave:16> close("all")
|
||||
octave:17> figure
|
||||
octave:18> figure()
|
||||
octave:19> close("all")
|
||||
octave:20> hist(1:10)
|
||||
octave:21> close all
|
||||
octave:22> a = hist(1:10)
|
||||
a =
|
||||
|
||||
1 1 1 1 1 1 1 1 1 1
|
||||
|
||||
octave:23> help find
|
||||
'find' is a built-in function from the file libinterp/corefcn/find.cc
|
||||
|
||||
-- IDX = find (X)
|
||||
-- IDX = find (X, N)
|
||||
-- IDX = find (X, N, DIRECTION)
|
||||
-- [i, j] = find (...)
|
||||
-- [i, j, v] = find (...)
|
||||
Return a vector of indices of nonzero elements of a matrix, as a
|
||||
row if X is a row vector or as a column otherwise.
|
||||
|
||||
To obtain a single index for each matrix element, Octave pretends
|
||||
that the columns of a matrix form one long vector (like Fortran
|
||||
arrays are stored). For example:
|
||||
|
||||
find (eye (2))
|
||||
=> [ 1; 4 ]
|
||||
|
||||
If two inputs are given, N indicates the maximum number of elements
|
||||
to find from the beginning of the matrix or vector.
|
||||
|
||||
If three inputs are given, DIRECTION should be one of "first" or
|
||||
"last", requesting only the first or last N indices, respectively.
|
||||
However, the indices are always returned in ascending order.
|
||||
|
||||
If two outputs are requested, 'find' returns the row and column
|
||||
indices of nonzero elements of a matrix. For example:
|
||||
|
||||
[i, j] = find (2 * eye (2))
|
||||
=> i = [ 1; 2 ]
|
||||
=> j = [ 1; 2 ]
|
||||
|
||||
If three outputs are requested, 'find' also returns a vector
|
||||
containing the nonzero values. For example:
|
||||
|
||||
[i, j, v] = find (3 * eye (2))
|
||||
=> i = [ 1; 2 ]
|
||||
=> j = [ 1; 2 ]
|
||||
=> v = [ 3; 3 ]
|
||||
|
||||
If X is a multi-dimensional array of size m x n x p x ..., J
|
||||
contains the column locations as if X was flattened into a
|
||||
two-dimensional matrix of size m x (n + p + ...).
|
||||
|
||||
Note that this function is particularly useful for sparse matrices,
|
||||
as it extracts the nonzero elements as vectors, which can then be
|
||||
used to create the original matrix. For example:
|
||||
|
||||
sz = size (a);
|
||||
[i, j, v] = find (a);
|
||||
b = sparse (i, j, v, sz(1), sz(2));
|
||||
|
||||
See also: nonzeros.
|
||||
|
||||
Additional help for built-in functions and operators is
|
||||
available in the online version of the manual. Use the command
|
||||
'doc <topic>' to search the manual index.
|
||||
|
||||
Help and information about Octave is also available on the WWW
|
||||
at https://www.octave.org and via the help@octave.org
|
||||
mailing list.
|
||||
octave:24> cube = @(x) x.^3;
|
||||
octave:25> cube
|
||||
cube =
|
||||
|
||||
@(x) x .^ 3
|
||||
|
||||
octave:26> cube(3)
|
||||
ans = 27
|
||||
octave:27> paraboloid = @(x, y) x.^2 + y.^2;
|
||||
octave:28> paraboloid(3, 4)
|
||||
ans = 25
|
||||
octave:29> @(x) x.^3
|
||||
ans =
|
||||
octave:35> a = 9
|
||||
a = 9
|
||||
octave:36> capture = @() a;
|
||||
octave:37> capture
|
||||
capture =
|
||||
|
||||
@() a
|
||||
|
||||
octave:38> capture()
|
||||
ans = 9
|
||||
octave:39> capture = @() 9
|
||||
capture =
|
||||
|
||||
@() 9
|
||||
|
||||
octave:40> capture()
|
||||
ans = 9
|
||||
octave:41> capture = @() a;
|
||||
octave:42> capture()
|
||||
ans = 9
|
||||
octave:43> a = 3
|
||||
a = 3
|
||||
octave:44> capture()
|
||||
ans = 9
|
||||
octave:45> n = 4
|
||||
n = 4
|
||||
octave:46> n = 2
|
||||
n = 2
|
||||
octave:47> pown = @(x) x.^n
|
||||
pown =
|
||||
|
||||
@(x) x .^ n
|
||||
|
||||
octave:48> pown(3)
|
||||
ans = 9
|
||||
octave:49> n = 4
|
||||
n = 4
|
||||
octave:50> pown(3)
|
||||
ans = 9
|
||||
octave:51>
|
||||
^[[200~compose = @(f, g) @(x) f(g(x));^[[201~octave:51>
|
||||
octave:51>
|
||||
octave:51>
|
||||
octave:51>
|
||||
octave:51> compose = @(f, g) @(x) f(g(x));
|
||||
octave:52>
|
||||
octave:52>
|
||||
octave:52>
|
||||
octave:52>
|
||||
octave:52>
|
||||
octave:52> add_three = @(x) x + 3;
|
||||
times_four = @(x) x * 4;
|
||||
x_times_four_plus_three = compose(add_three, times_four);
|
||||
octave:55> x_times_four_plus_three
|
||||
x_times_four_plus_three =
|
||||
|
||||
@(x) f (g (x))
|
||||
|
||||
octave:56> function y = times_four_plus_three(x)
|
||||
> x2 = x.*4;
|
||||
> y = x2 + 3;
|
||||
> end
|
||||
octave:57> times_four_plus_three(1)
|
||||
ans = 7
|
||||
octave:58> answer = times_four_plus_three(1)
|
||||
answer = 7
|
||||
octave:59> function [y, z] = mystery_math(p, q)
|
||||
> y = p + q;
|
||||
> z = p - q;
|
||||
> disp('did the math!');
|
||||
> end
|
||||
octave:60> mystery_math(3, 4)
|
||||
did the math!
|
||||
ans = 7
|
||||
octave:61> [val1, val2] = mystery_math(3, 4)
|
||||
did the math!
|
||||
val1 = 7
|
||||
val2 = -1
|
||||
octave:62>
|
||||
|
||||
[cat@lazarus:~/classes/ece210-materials/2024-van-west/lessons/lesson04]
|
||||
$ ls
|
||||
BasicClass.m datatypes.m for_loops.m lecture.txt
|
||||
controlflow.m distance.m funnnnnn.m
|
||||
[cat@lazarus:~/classes/ece210-materials/2024-van-west/lessons/lesson04]
|
||||
$ cat distance.m
|
||||
% In a file like this one (which only defines normal functions, and in which
|
||||
% the first function is hononymous with the filename), the first function is a
|
||||
% public function, and all other functions are local helper functions.
|
||||
%
|
||||
% Note that you DO NOT want to put clc; clear; close all; at the top of a file
|
||||
% like this; it only makes sense to do this at the top of script files when you
|
||||
% want to clean your workspace!
|
||||
|
||||
% Calculate Euclidean distance
|
||||
% A public function, callable by other files and from the Command Window if
|
||||
% this is in the MATLAB path.
|
||||
function d = distance(x, y)
|
||||
d = sqrt(sq(x) + sq(y));
|
||||
end
|
||||
|
||||
% A local helper function. Only accessible within this file.
|
||||
function x = sq(x)
|
||||
x = x * x;
|
||||
end
|
||||
[cat@lazarus:~/classes/ece210-materials/2024-van-west/lessons/lesson04]
|
||||
$ octave
|
||||
GNU Octave, version 7.3.0
|
||||
Copyright (C) 1993-2022 The Octave Project Developers.
|
||||
This is free software; see the source code for copying conditions.
|
||||
There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or
|
||||
FITNESS FOR A PARTICULAR PURPOSE. For details, type 'warranty'.
|
||||
|
||||
Octave was configured for "x86_64-pc-linux-gnu".
|
||||
|
||||
Additional information about Octave is available at https://www.octave.org.
|
||||
|
||||
Please contribute if you find this software useful.
|
||||
For more information, visit https://www.octave.org/get-involved.html
|
||||
|
||||
Read https://www.octave.org/bugs.html to learn how to submit bug reports.
|
||||
For information about changes from previous versions, type 'news'.
|
||||
|
||||
octave:1> who
|
||||
octave:2> distance(3, 4)
|
||||
ans = 5
|
||||
octave:3> path
|
||||
|
||||
Octave's search path contains the following directories:
|
||||
|
||||
.
|
||||
/usr/lib/x86_64-linux-gnu/octave/7.3.0/site/oct/x86_64-pc-linux-gnu
|
||||
/usr/lib/x86_64-linux-gnu/octave/site/oct/api-v57/x86_64-pc-linux-gnu
|
||||
/usr/lib/x86_64-linux-gnu/octave/site/oct/x86_64-pc-linux-gnu
|
||||
/usr/share/octave/7.3.0/site/m
|
||||
/usr/share/octave/site/api-v57/m
|
||||
/usr/share/octave/site/m
|
||||
/usr/share/octave/site/m/startup
|
||||
/usr/lib/x86_64-linux-gnu/octave/7.3.0/oct/x86_64-pc-linux-gnu
|
||||
/usr/share/octave/7.3.0/m
|
||||
/usr/share/octave/7.3.0/m/audio
|
||||
/usr/share/octave/7.3.0/m/deprecated
|
||||
/usr/share/octave/7.3.0/m/elfun
|
||||
/usr/share/octave/7.3.0/m/general
|
||||
/usr/share/octave/7.3.0/m/geometry
|
||||
/usr/share/octave/7.3.0/m/gui
|
||||
/usr/share/octave/7.3.0/m/help
|
||||
/usr/share/octave/7.3.0/m/image
|
||||
/usr/share/octave/7.3.0/m/io
|
||||
/usr/share/octave/7.3.0/m/java
|
||||
/usr/share/octave/7.3.0/m/legacy
|
||||
/usr/share/octave/7.3.0/m/linear-algebra
|
||||
/usr/share/octave/7.3.0/m/miscellaneous
|
||||
/usr/share/octave/7.3.0/m/ode
|
||||
/usr/share/octave/7.3.0/m/optimization
|
||||
/usr/share/octave/7.3.0/m/path
|
||||
/usr/share/octave/7.3.0/m/pkg
|
||||
/usr/share/octave/7.3.0/m/plot
|
||||
/usr/share/octave/7.3.0/m/plot/appearance
|
||||
/usr/share/octave/7.3.0/m/plot/draw
|
||||
/usr/share/octave/7.3.0/m/plot/util
|
||||
/usr/share/octave/7.3.0/m/polynomial
|
||||
/usr/share/octave/7.3.0/m/prefs
|
||||
/usr/share/octave/7.3.0/m/profiler
|
||||
/usr/share/octave/7.3.0/m/set
|
||||
/usr/share/octave/7.3.0/m/signal
|
||||
/usr/share/octave/7.3.0/m/sparse
|
||||
/usr/share/octave/7.3.0/m/specfun
|
||||
/usr/share/octave/7.3.0/m/special-matrix
|
||||
/usr/share/octave/7.3.0/m/startup
|
||||
/usr/share/octave/7.3.0/m/statistics
|
||||
/usr/share/octave/7.3.0/m/strings
|
||||
/usr/share/octave/7.3.0/m/testfun
|
||||
/usr/share/octave/7.3.0/m/time
|
||||
/usr/share/octave/7.3.0/m/web
|
||||
/usr/share/octave/7.3.0/data
|
||||
|
||||
octave:4> power_to_dB = @(p) 10*log10(p);
|
||||
octave:5> dB_to_power = @(db) 10.^(db./10);
|
||||
octave:6> power_to_dB(10)
|
||||
ans = 10
|
||||
octave:7> power_to_dB(1000)
|
||||
ans = 30
|
||||
octave:8> power_to_dB(100)
|
||||
ans = 20
|
||||
octave:9> dB_to_power(10)
|
||||
ans = 10
|
||||
octave:10> dB_to_power(-10)
|
||||
ans = 0.1000
|
||||
octave:11> for v = [1 2 5 7]
|
||||
> v
|
||||
> end
|
||||
v = 1
|
||||
v = 2
|
||||
v = 5
|
||||
v = 7
|
||||
octave:12> for i = 1:10
|
||||
> i + 3
|
||||
> end
|
||||
ans = 4
|
||||
ans = 5
|
||||
ans = 6
|
||||
ans = 7
|
||||
ans = 8
|
||||
ans = 9
|
||||
ans = 10
|
||||
ans = 11
|
||||
ans = 12
|
||||
ans = 13
|
||||
octave:13> total = 0
|
||||
total = 0
|
||||
octave:14> for i = 1:10
|
||||
> total = total + i
|
||||
> end
|
||||
total = 1
|
||||
total = 3
|
||||
total = 6
|
||||
total = 10
|
||||
total = 15
|
||||
total = 21
|
||||
total = 28
|
||||
total = 36
|
||||
total = 45
|
||||
total = 55
|
||||
octave:15> sum(1:10)
|
||||
ans = 55
|
||||
octave:16> 1 < 2
|
||||
ans = 1
|
||||
octave:17> who
|
||||
Variables visible from the current scope:
|
||||
|
||||
ans dB_to_power i power_to_dB total v
|
||||
|
||||
octave:18> whos
|
||||
Variables visible from the current scope:
|
||||
|
||||
variables in scope: top scope
|
||||
|
||||
Attr Name Size Bytes Class
|
||||
==== ==== ==== ===== =====
|
||||
ans 1x1 1 logical
|
||||
dB_to_power 1x1 0 function_handle
|
||||
i 1x1 8 double
|
||||
power_to_dB 1x1 0 function_handle
|
||||
total 1x1 8 double
|
||||
v 1x1 8 double
|
||||
|
||||
Total is 6 elements using 25 bytes
|
||||
|
||||
octave:19> if 1 < 2
|
||||
> disp('math still works today');
|
||||
> else
|
||||
> disp('oh no');
|
||||
> end
|
||||
math still works today
|
||||
octave:20> i = 0
|
||||
i = 0
|
||||
octave:21> while i < 10
|
||||
> i = i + 1
|
||||
> end
|
||||
i = 1
|
||||
i = 2
|
||||
i = 3
|
||||
i = 4
|
||||
i = 5
|
||||
i = 6
|
||||
i = 7
|
||||
i = 8
|
||||
i = 9
|
||||
i = 10
|
||||
octave:22> try
|
||||
> a = [1 2; 3 4];
|
||||
> b = [1 2 3 4];
|
||||
> c = a*b;
|
||||
> catch err
|
||||
> disp('yo! don't do that!')
|
||||
error: parse error:
|
||||
|
||||
syntax error
|
||||
|
||||
>>> disp('yo! don't do that!')
|
||||
^
|
||||
octave:22> try
|
||||
> a = [1 2; 3 4];
|
||||
> b = [1 2 3 4];
|
||||
> c = a*b;
|
||||
> catch err
|
||||
> disp('yo! do not do that!')
|
||||
> end
|
||||
yo! do not do that!
|
||||
octave:23> a
|
||||
a =
|
||||
|
||||
1 2
|
||||
3 4
|
||||
|
||||
octave:24> b
|
||||
b =
|
||||
|
||||
1 2 3 4
|
||||
|
||||
octave:25> a*b
|
||||
error: operator *: nonconformant arguments (op1 is 2x2, op2 is 1x4)
|
||||
octave:26> clear
|
||||
octave:27> whos
|
||||
octave:28> a = 10
|
||||
a = 10
|
||||
octave:29> class(a)
|
||||
ans = double
|
||||
octave:30> b = int8(a)
|
||||
b = 10
|
||||
octave:31> class(b)
|
||||
ans = int8
|
||||
octave:32> b + .5
|
||||
ans = 11
|
||||
octave:33> whos
|
||||
Variables visible from the current scope:
|
||||
|
||||
variables in scope: top scope
|
||||
|
||||
Attr Name Size Bytes Class
|
||||
==== ==== ==== ===== =====
|
||||
a 1x1 8 double
|
||||
ans 1x1 1 int8
|
||||
b 1x1 1 int8
|
||||
|
||||
Total is 3 elements using 10 bytes
|
||||
|
||||
octave:34>
|
||||
octave:34>
|
||||
octave:34>
|
||||
^[[200~imshow(uint8(rand(128, 128, 3)));^[[201~octave:34>
|
||||
octave:34>
|
||||
octave:34> imshow(uint8(rand(128, 128, 3)));
|
||||
octave:35> close all
|
||||
octave:36>
|
||||
^[[200~imshow(double(rand(128, 128, 3)));^[[201~octave:36>
|
||||
octave:36>
|
||||
octave:36>
|
||||
octave:36>
|
||||
octave:36> imshow(double(rand(128, 128, 3)));
|
||||
octave:37> close all
|
||||
octave:38> imshow(uint8(rand(128, 128, 3)));
|
||||
octave:39> close all
|
||||
octave:40> imshow(uint8(rand(128, 128, 3)));
|
||||
octave:40> eps
|
||||
ans = 2.2204e-16
|
||||
octave:41> eps(1)
|
||||
ans = 2.2204e-16
|
||||
octave:42> eps(.001)
|
||||
ans = 2.1684e-19
|
||||
octave:43> eps(10000)
|
||||
ans = 1.8190e-12
|
||||
octave:44> eps(1e100)
|
||||
ans = 1.9427e+84
|
||||
octave:45> 10^(10^10)
|
||||
ans = Inf
|
||||
octave:46> a = 5
|
||||
a = 5
|
||||
octave:47> b = "hello!"
|
||||
b = hello!
|
||||
octave:48> s = struct('a', 5, 'b', "hello!")
|
||||
s =
|
||||
|
||||
scalar structure containing the fields:
|
||||
|
||||
a = 5
|
||||
b = hello!
|
||||
|
||||
octave:49> s
|
||||
s =
|
||||
|
||||
scalar structure containing the fields:
|
||||
|
||||
a = 5
|
||||
b = hello!
|
||||
|
||||
octave:50> s.a
|
||||
ans = 5
|
||||
octave:51> s.b
|
||||
ans = hello!
|
||||
octave:52>
|
Reference in New Issue
Block a user