Sagebrush · Examples · Notebooks

MATLAB

MATLAB programs: matrices, linear algebra and functions defined in a cell.

notebook · MATLAB · intro · by Sagebrush · MIT license

basicslinear algebra

Download (ZIP)Source on GitHub

Preview

MATLAB

MATLAB programs, translated to Python in this page and run on Sagebrush's numpy. Values print as MATLAB prints them (checked against GNU Octave and MATLAB's documentation), variables and functions stay for the next cells, and figures show when a cell ends.

% Matrices and linear algebra
A = [4 -2; 1 1]
x = A \ [2; 3]
[V, D] = eig([2 1; 1 3]);
diag(D)'
A =

     4    -2
     1     1

x =

    1.3333
    1.6667


ans =

    1.3820    3.6180

% A function defined in a cell is there for the cells after it
function y = collatz(n)
  y = n;
  while n ~= 1
    if mod(n, 2) == 0, n = n / 2; else, n = 3 * n + 1; end
    y(end + 1) = n;
  end
end
c = collatz(27);
fprintf('%d steps, peak %d\n', numel(c) - 1, max(c))
111 steps, peak 9232
% Structs and cell arrays
s = struct('name', {'Ada', 'Emmy'}, 'born', {1815, 1882});
for k = 1:numel(s)
  fprintf('%s was born in %d\n', s(k).name, s(k).born);
end
names = upper({s.name})
Ada was born in 1815
Emmy was born in 1882

names =

  1×2 cell array

    {'ADA'}    {'EMMY'}

% Figures
x = linspace(0, 2*pi, 200);
plot(x, sin(x), x, cos(x), '--')
legend('sin', 'cos'); title('Figures show when the cell ends'); grid on
Plot: "Figures show when the cell ends"; line "sin" through 200 points, line "cos" through 200 points; x from 0 to 7, y from -1 to 1
% Surfaces in 3-D
[X, Y, Z] = peaks(40);
surf(X, Y, Z)
colorbar
Figure with 2 plots: line through 76 points, line through 24 points, surface of 1521 faces, text "-3", text "-2", text "-1", text "0", text "1", 14 more; x from -0.9462 to 0.9462, y from -1.004 to 0.9155 | 64 bars; x from 0 to 1, y from -6.55 to 8.049

Files

Open the ZIP's notebook in Sagebrush (File, Open) to run and change it.