Using Octave: Difference between revisions

From Octave
Jump to navigation Jump to search
Tag: Reverted
m (Reverted edits by 200.133.9.19 (talk) to last revision by 217.158.171.38)
Tag: Rollback
 
Line 21: Line 21:
Read more [https://www.gnu.org/software/octave/doc/interpreter/Comments.html about comments].
Read more [https://www.gnu.org/software/octave/doc/interpreter/Comments.html about comments].


% Função e derivada
= Command evaluation =
f = @(x) 1 - x^3;      % f(x) = 1 - x^3
f_prime = @(x) -3*x^2; % f'(x) = -3*x^2


% Condição inicial e tolerância
The output of every command is printed to the console unless terminated with
x0 = 2% ponto inicial
a semicolon <code>;</code>. The [https://www.gnu.org/software/octave/doc/interpreter/XREFdisp.html disp] command can be used to print output
tolerancia = 1e-6; % tolerância
anywhere. Use [https://www.gnu.org/software/octave/doc/interpreter/XREFquit.html exit] or [https://www.gnu.org/software/octave/doc/interpreter/XREFquit.html quit] to quit the console.
max_iter = 100;  % máximo de iterações para evitar loop infinito
Read more [https://www.gnu.org/software/octave/doc/interpreter/Simple-Examples.html about command evaluation].
iter = 0;  % contador de iterações
erro = inf;  % inicializando o erro como infinito


% Método de Newton-Raphson
<syntaxhighlight lang="octave">t = 99 + 1  # prints 't = 100'</syntaxhighlight>
while erro > tolerancia && iter < max_iter
<syntaxhighlight lang="text">t 100</syntaxhighlight>
    iter = iter + 1; % incrementar contador de iteração
    x1 = x0 - f(x0) / f_prime(x0);  % fórmula de Newton-Raphson
    erro = abs(x1 - x0);  % erro absoluto entre iterações
    x0 = x1; % atualizar x0 para o novo valor
end


% Resultado
<syntaxhighlight lang="octave">t = 99 + 1; # nothing is printed
disp(['Raiz aproximada: ', num2str(x1)]);
disp(t);</syntaxhighlight>
disp(['Número de iterações: ', num2str(iter)]);
<syntaxhighlight lang="text"> 100</syntaxhighlight>


= Elementary math =
= Elementary math =
Line 159: Line 150:




% Função f(x) = 1 - x^3
= Plotting =
f = @(x) 1 - x^3;         


% Derivada de f(x) -> f'(x) = -3*x^2
The function [https://www.gnu.org/software/octave/doc/interpreter/XREFplot.html plot] can be called with vector arguments to
f_prime = @(x) -3*x^2;
create 2D line and scatter plots.  Read more
[https://www.gnu.org/software/octave/doc/interpreter/Two_002dDimensional-Plots.html about plotting].


% Função para aplicar o Método de Newton-Raphson
<syntaxhighlight lang="octave">plot (i / 10, w);
function [raiz, num_iteracoes, iteracoes_x, iteracoes_y] = newton_raphson(x0, tolerancia)
title ('w = sin (i / 10)');
    % Inicializar variáveis
xlabel ('i / 10');
    iter = 0;                  % Contador de iterações
ylabel ('w');</syntaxhighlight>
    erro = inf;                % Inicializa o erro como infinito
    x = x0;                    % Definir o ponto inicial
    iteracoes_x = x;           % Inicializar vetor de iterações para o gráfico
    iteracoes_y = f(x);        % Inicializar valores de f(x) para o gráfico
   
    % Iterar até que o erro seja menor que a tolerância
    while erro > tolerancia && iter < 100
        iter = iter + 1;                          % Incrementa a iteração
        x_new = x - f(x) / f_prime(x);            % Fórmula de Newton-Raphson
        erro = abs(x_new - x);                   % Calcula o erro absoluto
        x = x_new;                                % Atualiza x
       
        % Armazena os valores de x e f(x) para o gráfico
        iteracoes_x = [iteracoes_x, x];
        iteracoes_y = [iteracoes_y, f(x)];
    end
   
    % Retorna a raiz aproximada, número de iterações e os valores das iterações
    raiz = x;                                    % Raiz aproximada
    num_iteracoes = iter;                        % Número de iterações
end


% Condições de cada caso
[[File:Using octave-1.png|thumb|center]]
% Caso 1: x0 = 2 e tolerância = 1e-6
x0_case1 = 2;
tolerancia_case1 = 1e-6;
 
% Caso 2: x0 = 7 e tolerância = 1e-3
x0_case2 = 7;
tolerancia_case2 = 1e-3;
 
% Resultado para o primeiro caso (x0 = 2, tolerância = 1e-6)
[raiz_case1, iter_case1, iteracoes_x_case1, iteracoes_y_case1] = newton_raphson(x0_case1, tolerancia_case1);
disp(['Caso 1: Raiz aproximada: ', num2str(raiz_case1)]);
disp(['Número de iterações: ', num2str(iter_case1)]);
 
% Resultado para o segundo caso (x0 = 7, tolerância = 1e-3)
[raiz_case2, iter_case2, iteracoes_x_case2, iteracoes_y_case2] = newton_raphson(x0_case2, tolerancia_case2);
disp(['Caso 2: Raiz aproximada: ', num2str(raiz_case2)]);
disp(['Número de iterações: ', num2str(iter_case2)]);
 
% Plotagem do gráfico
figure;
 
% Caso 1: Plotando as iterações
subplot(2,1,1);
plot(iteracoes_x_case1, iteracoes_y_case1, '-o', 'LineWidth', 2, 'MarkerSize', 6);
title('Método de Newton-Raphson - Caso 1 (x0 = 2)');
xlabel('Iterações (x)');
ylabel('f(x)');
grid on;
 
% Caso 2: Plotando as iterações
subplot(2,1,2);
plot(iteracoes_x_case2, iteracoes_y_case2, '-o', 'LineWidth', 2, 'MarkerSize', 6);
title('Método de Newton-Raphson - Caso 2 (x0 = 7)');
xlabel('Iterações (x)');
ylabel('f(x)');
grid on;


= Strings =
= Strings =

Latest revision as of 20:42, 10 December 2024

First, follow the installation instructions for:

or consult the GNU Octave manual to install GNU Octave on your system. Then, start the GNU Octave by clicking the icon in the programs menu or launch the interactive prompt by typing octave in a terminal. See the manual page on running Octave.

The GNU Octave graphical user interface (GUI).

Variable Assignment[edit]

Assign values to variables with = (Note: assignment is pass-by-value). Read more about variables.

a = 1;

Comments[edit]

# or % start a comment line, that continues to the end of the line. Read more about comments.

Command evaluation[edit]

The output of every command is printed to the console unless terminated with a semicolon ;. The disp command can be used to print output anywhere. Use exit or quit to quit the console. Read more about command evaluation.

t = 99 + 1  # prints 't = 100'
t =  100
t = 99 + 1; # nothing is printed
disp(t);
 100

Elementary math[edit]

Many mathematical operators are available in addition to the standard arithmetic. Operations are floating-point. Read more about elementary math.

x = 3/4 * pi;
y = sin (x)
y =  0.70711



Matrices[edit]

Arrays in Octave are called matrices. One-dimensional matrices are referred to as vectors. Use a space or a comma , to separate elements in a row and semicolon ; to start a new row. Read more about matrices.

rowVec = [8 6 4]
rowVec =
   8   6   4
columnVec = [8; 6; 4]
columnVec =
   8
   6
   4
mat = [8 6 4; 2 0 -2]
mat =
   8   6   4
   2   0  -2
size(mat)
ans =
   2   3
length(rowVec)
ans =  3


Linear Algebra[edit]

Many common linear algebra operations are simple to program using Octave’s matrix syntax. Read more about linear algebra.

columnVec * rowVec
ans =
   64   48   32
   48   36   24
   32   24   16
rowVec * columnVec
ans =  116
columnVec'
ans =
   8   6   4

Accessing Elements[edit]

Octave is 1-indexed. Matrix elements are accessed as matrix(rowNum, columnNum). Read more about accessing elements.

mat(2,3)
ans = -2


Control flow with loops[edit]

Octave supports for and while loops, as well as other control flow structures. Read more about control flow.

x = zeros (50,1);
for i = 1:2:100 # iterate from 1 to 100 with step size 2
  x(i) = i^2;
endfor

y = zeros (50,1);
k = 1;
step = 2;
while (k <= 100)
  y(k) = k^2;
  k = k + step;
endwhile

Vectorization[edit]

For-loops can often be replaced or simplified using vector syntax. The operators *, /, and ^ all support element-wise operations writing a dot . before the operators. Many other functions operate element-wise by default (sin, +, -, etc.). Read more about vectorization.

i = 1:2:100;      # create an array with 50-elements
x = i.^2;         # each element is squared
y = x + 9;        # add 9 to each element
z = y./i;         # divide each element in y by the corresponding value in i
w = sin (i / 10); # take the sine of each element divided by 10


Plotting[edit]

The function plot can be called with vector arguments to create 2D line and scatter plots. Read more about plotting.

plot (i / 10, w);
title ('w = sin (i / 10)');
xlabel ('i / 10');
ylabel ('w');
Using octave-1.png

Strings[edit]

Strings are simply arrays of characters. Strings can be composed using C-style formatting with sprintf or fprintf. Read more about strings.

firstString = "hello world";
secondString = "!";
[firstString, secondString] # concatenate both strings
ans = hello world!
fprintf ("%s %.10f \n", "The number is:", 10)
The number is: 10.0000000000


If-else[edit]

Conditional statements can be used to create branching logic in your code. Read more in the manual.

# Print 'Foo'      if divisible by 7,
#       'Fizz'     if divisible by 3,
#       'Buzz'     if divisible by 5,
#       'FizzBuzz' if divisible by 3 and 5
for i = 1:1:20
  outputString = "";
  if (rem (i, 3) == 0)  # rem is the remainder function
    outputString = [outputString, "Fizz"];
  endif
  if (rem (i, 5) == 0)
    outputString = [outputString, "Buzz"];
  elseif (rem(i,7) == 0)
    outputString = "Foo";
  else
    outputString = outputString;
  endif
  fprintf("i=%g: %s \n", i, outputString);
endfor
i=1:  
i=2:  
i=3: Fizz 
i=4:  
i=5: Buzz 
i=6: Fizz 
i=7: Foo 
i=8:  
i=9: Fizz 
i=10: Buzz 
i=11:  
i=12: Fizz 
i=13:  
i=14: Foo 
i=15: FizzBuzz 
i=16:  
i=17:  
i=18: Fizz 
i=19:  
i=20: Buzz


Getting Help[edit]

The help and doc commands can be invoked at the Octave prompt to print documentation for any function.

help plot
doc plot


Octave packages[edit]

Community-developed packages can be added from the Octave Packages website to extend the functionality of Octave’s core library. (Matlab users: Packages act similarly to Matlab’s toolboxes.) The pkg command is used to manage these packages. For example, to use the image processing library visit its page on Octave Packages, copy the install command and run it in octave

pkg install "https://downloads.sourceforge.net/project/octave/Octave%20Forge%20Packages/Individual%20Package%20Releases/image-2.14.0.tar.gz" # install package
pkg load image           # load new functions into workspace

Read more about packages.

Octave User Codes[edit]

There are also User Codes available for GNU Octave which are not part of the core program or any of the packages.

See Category User Codes.