1
0
mirror of https://github.com/adambard/learnxinyminutes-docs.git synced 2025-08-12 09:44:24 +02:00

Matlab portuguese translation

The markdown is completely translated
This commit is contained in:
Claudson Martins
2015-10-18 13:41:14 -03:00
parent b0ae4db558
commit 603d72e9ea

View File

@@ -26,11 +26,11 @@ com
algo assim algo assim
%} %}
% comandos podem ocupar várinhas linhas, usando '...': % Comandos podem ocupar várinhas linhas, usando '...':
a = 1 + 2 + ... a = 1 + 2 + ...
+ 4 + 4
% comandos podem ser passados para o sistema operacional % Comandos podem ser passados para o sistema operacional
!ping google.com !ping google.com
who % Exibe todas as variáveis na memória who % Exibe todas as variáveis na memória
@@ -46,7 +46,7 @@ ctrl-c % Aborta a computação atual
edit('minhafuncao.m') % Abre a função/script no editor edit('minhafuncao.m') % Abre a função/script no editor
type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando
profile on % Ativa o perfil de código profile on % Ativa o perfil de código
profile off % Desativa o perfil de código profile off % Desativa o perfil de código
profile viewer % Visualiza os resultados na janela de Profiler profile viewer % Visualiza os resultados na janela de Profiler
@@ -77,97 +77,98 @@ c = exp(a)*sin(pi/2) % c = 7.3891
load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula
% Sintaxe de comando: % Sintaxe de comando:
load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas
% Observe a falta de aspas no formulário de comando: entradas são sempre % Observe a falta de aspas na forma de comando: entradas são sempre passadas
% passadas como texto literal - não pode passar valores de variáveis. % como texto literal - não pode passar valores de variáveis.
% Além disso, não pode receber saída: % Além disso, não pode receber saída:
[V,D] = eig(A); % this has no equivalent in command form [V,D] = eig(A); % Isto não tem um equivalente na forma de comando
[~,D] = eig(A); % if you only want D and not V [~,D] = eig(A); % Se você só deseja D e não V
% Logicals % Operadores Lógicos e Relacionais
1 > 5 % ans = 0 1 > 5 % Resposta = 0
10 >= 10 % ans = 1 10 >= 10 % Resposta = 1
3 ~= 4 % Not equal to -> ans = 1 3 ~= 4 % Diferente de -> Resposta = 1
3 == 3 % equal to -> ans = 1 3 == 3 % Igual a -> Resposta = 1
3 > 1 && 4 > 1 % AND -> ans = 1 3 > 1 && 4 > 1 % E -> Resposta = 1
3 > 1 || 4 > 1 % OR -> ans = 1 3 > 1 || 4 > 1 % OU -> Resposta = 1
~1 % NOT -> ans = 0 ~1 % NOT -> Resposta = 0
% Logicals can be applied to matrices: % Operadores Lógicos e Relacionais podem ser aplicados a matrizes
A > 5 A > 5
% for each element, if condition is true, that element is 1 in returned matrix % Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada
A( A > 5 ) A( A > 5 )
% returns a vector containing the elements in A for which condition is true % Retorna um vetor com os elementos de A para os quais a condição é verdadeira
% Strings % Cadeias de caracteres (Strings)
a = 'MyString' a = 'MinhaString'
length(a) % ans = 8 length(a) % Resposta = 11
a(2) % ans = y a(2) % Resposta = i
[a,a] % ans = MyStringMyString [a,a] % Resposta = MinhaStringMinhaString
% Cells % Vetores de células
a = {'one', 'two', 'three'} a = {'um', 'dois', 'três'}
a(1) % ans = 'one' - returns a cell a(1) % Resposta = 'um' - retorna uma célula
char(a(1)) % ans = one - returns a string char(a(1)) % Resposta = um - retorna uma string
% Structures % Estruturas
A.b = {'one','two'}; A.b = {'um','dois'};
A.c = [1 2]; A.c = [1 2];
A.d.e = false; A.d.e = false;
% Vectors % Vetores
x = [4 32 53 7 1] x = [4 32 53 7 1]
x(2) % ans = 32, indices in Matlab start 1, not 0 x(2) % Resposta = 32, índices no Matlab começam por 1, não 0
x(2:3) % ans = 32 53 x(2:3) % Resposta = 32 53
x(2:end) % ans = 32 53 7 1 x(2:end) % Resposta = 32 53 7 1
x = [4; 32; 53; 7; 1] % Column vector x = [4; 32; 53; 7; 1] % Vetor coluna
x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
% Matrices % Matrizes
A = [1 2 3; 4 5 6; 7 8 9] A = [1 2 3; 4 5 6; 7 8 9]
% Rows are separated by a semicolon; elements are separated with space or comma % Linhas são separadas por um ponto e vírgula;
% Elementos são separados com espaço ou vírgula
% A = % A =
% 1 2 3 % 1 2 3
% 4 5 6 % 4 5 6
% 7 8 9 % 7 8 9
A(2,3) % ans = 6, A(row, column) A(2,3) % Resposta = 6, A(linha, coluna)
A(6) % ans = 8 A(6) % Resposta = 8
% (implicitly concatenates columns into vector, then indexes into that) % (implicitamente encadeia as colunas do vetor, e então as indexa)
A(2,3) = 42 % Update row 2 col 3 with 42 A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42
% A = % A =
% 1 2 3 % 1 2 3
% 4 5 42 % 4 5 42
% 7 8 9 % 7 8 9
A(2:3,2:3) % Creates a new matrix from the old one A(2:3,2:3) % Cria uma nova matriz a partir da antiga
%ans = %Resposta =
% 5 42 % 5 42
% 8 9 % 8 9
A(:,1) % All rows in column 1 A(:,1) % Todas as linhas na coluna 1
%ans = %Resposta =
% 1 % 1
% 4 % 4
% 7 % 7
A(1,:) % All columns in row 1 A(1,:) % Todas as colunas na linha 1
%ans = %Resposta =
% 1 2 3 % 1 2 3
[A ; A] % Concatenation of matrices (vertically) [A ; A] % Concatenação de matrizes (verticalmente)
%ans = %Resposta =
% 1 2 3 % 1 2 3
% 4 5 42 % 4 5 42
@@ -176,195 +177,197 @@ A(1,:) % All columns in row 1
% 4 5 42 % 4 5 42
% 7 8 9 % 7 8 9
% this is the same as % Isto é o mesmo de
vertcat(A,A); vertcat(A,A);
[A , A] % Concatenation of matrices (horizontally) [A , A] % Concatenação de matrizes (horizontalmente)
%ans = %Resposta =
% 1 2 3 1 2 3 % 1 2 3 1 2 3
% 4 5 42 4 5 42 % 4 5 42 4 5 42
% 7 8 9 7 8 9 % 7 8 9 7 8 9
% this is the same as % Isto é o mesmo de
horzcat(A,A); horzcat(A,A);
A(:, [3 1 2]) % Rearrange the columns of original matrix A(:, [3 1 2]) % Reorganiza as colunas da matriz original
%ans = %Resposta =
% 3 1 2 % 3 1 2
% 42 4 5 % 42 4 5
% 9 7 8 % 9 7 8
size(A) % ans = 3 3 size(A) % Resposta = 3 3
A(1, :) =[] % Delete the first row of the matrix A(1, :) =[] % Remove a primeira linha da matriz
A(:, 1) =[] % Delete the first column of the matrix A(:, 1) =[] % Remove a primeira coluna da matriz
transpose(A) % Transpose the matrix, which is the same as: transpose(A) % Transposta a matriz, que é o mesmo de:
A one A one
ctranspose(A) % Hermitian transpose the matrix ctranspose(A) % Transposta a matriz
% (the transpose, followed by taking complex conjugate of each element) % (a transposta, seguida pelo conjugado complexo de cada elemento)
% Element by Element Arithmetic vs. Matrix Arithmetic % Aritmética Elemento por Elemento vs. Aritmética com Matriz
% On their own, the arithmetic operators act on whole matrices. When preceded % Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando
% by a period, they act on each element instead. For example: % precedidos por um ponto, eles atuam em cada elemento. Por exemplo:
A * B % Matrix multiplication A * B % Multiplicação de matrizes
A .* B % Multiple each element in A by its corresponding element in B A .* B % Multiplica cada elemento em A por seu correspondente em B
% There are several pairs of functions, where one acts on each element, and % Existem vários pares de funções nas quais uma atua sob cada elemento, e a
% the other (whose name ends in m) acts on the whole matrix. % outra (cujo nome termina com m) age na matriz por completo.
exp(A) % exponentiate each element exp(A) % Exponencia cada elemento
expm(A) % calculate the matrix exponential expm(A) % Calcula o exponencial da matriz
sqrt(A) % take the square root of each element sqrt(A) % Tira a raiz quadrada de cada elemento
sqrtm(A) % find the matrix whose square is A sqrtm(A) % Procura a matriz cujo quadrado é A
% Plotting % Gráficos
x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1
y = sin(x); y = sin(x);
plot(x,y) plot(x,y)
xlabel('x axis') xlabel('eixo x')
ylabel('y axis') ylabel('eixo y')
title('Plot of y = sin(x)') title('Gráfico de y = sin(x)')
axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1
plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico
legend('Line 1 label', 'Line 2 label') % Label curves with a legend legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda
% Alternative method to plot multiple functions in one plot. % Método alternativo para traçar várias funções em um só gráfico:
% while 'hold' is on, commands add to existing graph rather than replacing it % Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico
% existente ao invés de o substituirem.
plot(x, y) plot(x, y)
hold on hold on
plot(x, z) plot(x, z)
hold off hold off
loglog(x, y) % A log-log plot loglog(x, y) % Plotar em escala loglog
semilogx(x, y) % A plot with logarithmic x-axis semilogx(x, y) % Um gráfico com eixo x logarítmico
semilogy(x, y) % A plot with logarithmic y-axis semilogy(x, y) % Um gráfico com eixo y logarítmico
fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5 fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5
grid on % Show grid; turn off with 'grid off' grid on % Exibe as linhas de grade; Oculta com 'grid off'
axis square % Makes the current axes region square axis square % Torna quadrada a região dos eixos atuais
axis equal % Set aspect ratio so data units are the same in every direction axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções
scatter(x, y); % Scatter-plot scatter(x, y); % Gráfico de dispersão ou bolha
hist(x); % Histogram hist(x); % Histograma
z = sin(x); z = sin(x);
plot3(x,y,z); % 3D line plot plot3(x,y,z); % Plotar em espaço em 3D
pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor
contour(A) % Contour plot of matrix contour(A) % Plotar de contorno da matriz
mesh(A) % Plot as a mesh surface mesh(A) % Plotar malha 3D
h = figure % Create new figure object, with handle f h = figure % Cria uma nova figura objeto, com identificador h
figure(h) % Makes the figure corresponding to handle h the current figure figure(h) % Cria uma nova janela de figura com h
close(h) % close figure with handle h close(h) % Fecha a figura h
close all % close all open figure windows close all % Fecha todas as janelas de figuras abertas
close % close current figure window close % Fecha a janela de figura atual
shg % bring an existing graphics window forward, or create new one if needed shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário
clf clear % clear current figure window, and reset most figure properties clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura
% Properties can be set and changed through a figure handle. % Propriedades podem ser definidas e alteradas através de um identificador.
% You can save a handle to a figure when you create it. % Você pode salvar um identificador para uma figura ao criá-la.
% The function gcf returns a handle to the current figure % A função gcf retorna o identificador da figura atual
h = plot(x, y); % you can save a handle to a figure when you create it h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la
set(h, 'Color', 'r') set(h, 'Color', 'r')
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black % 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto
set(h, 'LineStyle', '--') set(h, 'LineStyle', '--')
% '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha
get(h, 'LineStyle') get(h, 'LineStyle')
% The function gca returns a handle to the axes for the current figure % A função gca retorna o identificador para os eixos da figura atual
set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x
% To create a figure that contains several axes in tiled positions, use subplot % Para criar uma figura que contém vários gráficos use subplot, o qual divide
subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots % a janela de gráficos em m linhas e n colunas.
plot(x1); title('First Plot') % plot something in this position subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3
subplot(2,3,2); % select second position in the grid plot(x1); title('Primeiro Plot') % Plota algo nesta posição
plot(x2); title('Second Plot') % plot something there subplot(2,3,2); % Seleciona a segunda posição na grade
plot(x2); title('Segundo Plot') % Plota algo ali
% To use functions or scripts, they must be on your path or current directory % Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual
path % display current path path % Exibe o caminho atual
addpath /path/to/dir % add to path addpath /caminho/para/pasta % Adiciona o diretório ao caminho
rmpath /path/to/dir % remove from path rmpath /caminho/para/pasta % Remove o diretório do caminho
cd /path/to/move/into % change directory cd /caminho/para/mudar % Muda o diretório
% Variables can be saved to .mat files % Variáveis podem ser salvas em arquivos *.mat
save('myFileName.mat') % Save the variables in your Workspace save('meuArquivo.mat') % Salva as variáveis do seu Workspace
load('myFileName.mat') % Load saved variables into Workspace load('meuArquivo.mat') % Carrega as variáveis em seu Workspace
% M-file Scripts % Arquivos M (M-files)
% A script file is an external file that contains a sequence of statements. % Um arquivo de script é um arquivo externo contendo uma sequência de instruções.
% They let you avoid repeatedly typing the same code in the Command Window % Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos.
% Have .m extensions % Possuem a extensão *.m
% M-file Functions % Arquivos M de Funções (M-file Functions)
% Like scripts, and have the same .m extension % Assim como scripts e têm a mesma extensão *.m
% But can accept input arguments and return an output % Mas podem aceitar argumentos de entrada e retornar uma saída.
% Also, they have their own workspace (ie. different variable scope). % Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis).
% Function name should match file name (so save this example as double_input.m). % O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m)
% 'help double_input.m' returns the comments under line beginning function % 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função
function output = double_input(x) function output = dobra_entrada(x)
%double_input(x) returns twice the value of x %dobra_entrada(x) retorna duas vezes o valor de x
output = 2*x; output = 2*x;
end end
double_input(6) % ans = 12 dobra_entrada(6) % Resposta = 12
% You can also have subfunctions and nested functions. % Você também pode ter subfunções e funções aninhadas.
% Subfunctions are in the same file as the primary function, and can only be % Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados
% called by functions in the file. Nested functions are defined within another % por funções dentro do arquivo. Funções aninhadas são definidas dentro de
% functions, and have access to both its workspace and their own workspace. % outras funções, e têm acesso a ambos workspaces.
% If you want to create a function without creating a new file you can use an % Se você quer criar uma função sem criar um novo arquivo, você pode usar uma
% anonymous function. Useful when quickly defining a function to pass to % função anônima. Úteis para definir rapidamente uma função para passar a outra
% another function (eg. plot with fplot, evaluate an indefinite integral % função (ex. plotar com fplot, avaliar uma integral indefinida com quad,
% with quad, find roots with fzero, or find minimum with fminsearch). % procurar raízes com fzero, ou procurar mínimo com fminsearch).
% Example that returns the square of it's input, assigned to to the handle sqr: % Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr:
sqr = @(x) x.^2; sqr = @(x) x.^2;
sqr(10) % ans = 100 sqr(10) % Resposta = 100
doc function_handle % find out more doc function_handle % Saiba mais
% User input % Entrada do usuário
a = input('Enter the value: ') a = input('Digite o valor: ')
% Stops execution of file and gives control to the keyboard: user can examine % Para a execução do arquivo e passa o controle para o teclado: o usuário pode
% or change variables. Type 'return' to continue execution, or 'dbquit' to exit % examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair
keyboard keyboard
% Reading in data (also xlsread/importdata/imread for excel/CSV/image files) % Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem)
fopen(filename) fopen(nomedoarquivo)
% Output % Saída
disp(a) % Print out the value of variable a disp(a) % Imprime o valor da variável a
disp('Hello World') % Print out a string disp('Olá Mundo') % Imprime a string
fprintf % Print to Command Window with more control fprintf % Imprime na janela de comandos com mais controle
% Conditional statements (the parentheses are optional, but good style) % Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática)
if (a > 15) if (a > 15)
disp('Greater than 15') disp('Maior que 15')
elseif (a == 23) elseif (a == 23)
disp('a is 23') disp('a é 23')
else else
disp('neither condition met') disp('Nenhuma condição reconheceu')
end end
% Looping % Estruturas de Repetição
% NB. looping over elements of a vector/matrix is slow! % Nota: fazer o loop sobre elementos de um vetor/matriz é lento!
% Where possible, use functions that act on whole vector/matrix at once % Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez.
for k = 1:5 for k = 1:5
disp(k) disp(k)
end end
@@ -374,25 +377,26 @@ while (k < 5)
k = k + 1; k = k + 1;
end end
% Timing code execution: 'toc' prints the time since 'tic' was called % Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo
% passado desde que 'tic' foi chamado.
tic tic
A = rand(1000); A = rand(1000);
A*A*A*A*A*A*A; A*A*A*A*A*A*A;
toc toc
% Connecting to a MySQL Database % Conectando a uma base de dados MySQL
dbname = 'database_name'; dbname = 'nome_base_de_dados';
username = 'root'; username = 'root';
password = 'root'; password = 'root';
driver = 'com.mysql.jdbc.Driver'; driver = 'com.mysql.jdbc.Driver';
dburl = ['jdbc:mysql://localhost:8889/' dbname]; dburl = ['jdbc:mysql://localhost:8889/' dbname];
javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/
conn = database(dbname, username, password, driver, dburl); conn = database(dbname, username, password, driver, dburl);
sql = ['SELECT * from table_name where id = 22'] % Example sql statement sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL
a = fetch(conn, sql) %a will contain your data a = fetch(conn, sql) %a will contain your data
% Common math functions % Funções Matemáticas Comuns
sin(x) sin(x)
cos(x) cos(x)
tan(x) tan(x)
@@ -410,122 +414,122 @@ ceil(x)
floor(x) floor(x)
round(x) round(x)
rem(x) rem(x)
rand % Uniformly distributed pseudorandom numbers rand % Números pseudo-aleatórios uniformemente distribuídos
randi % Uniformly distributed pseudorandom integers randi % Inteiros pseudo-aleatórios uniformemente distribuídos
randn % Normally distributed pseudorandom numbers randn % Números pseudo-aleatórios normalmente distribuídos
% Common constants % Constantes Comuns
pi pi
NaN NaN
inf inf
% Solving matrix equations (if no solution, returns a least squares solution) % Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados)
% The \ and / operators are equivalent to the functions mldivide and mrdivide % Os operadores \ e / são equivalentes às funções mldivide e mrdivide
x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b.
x=b/A % Solves xA=b x=b/A % Resolve xA=b
inv(A) % calculate the inverse matrix inv(A) % Calcula a matriz inversa
pinv(A) % calculate the pseudo-inverse pinv(A) % Calcula a pseudo-inversa
% Common matrix functions % Funções Matriciais Comuns
zeros(m,n) % m x n matrix of 0's zeros(m,n) % Matriz de zeros m x n
ones(m,n) % m x n matrix of 1's ones(m,n) % Matriz de 1's m x n
diag(A) % Extracts the diagonal elements of a matrix A diag(A) % Extrai os elementos diagonais da matriz A
diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições
eye(m,n) % Identity matrix eye(m,n) % Matriz identidade
linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2
inv(A) % Inverse of matrix A inv(A) % Inverso da matriz A
det(A) % Determinant of A det(A) % Determinante da matriz A
eig(A) % Eigenvalues and eigenvectors of A eig(A) % Valores e vetores próprios de A
trace(A) % Trace of matrix - equivalent to sum(diag(A)) trace(A) % Traço da matriz - equivalente a sum(diag(A))
isempty(A) % Tests if array is empty isempty(A) % Testa se a matriz está vazia
all(A) % Tests if all elements are nonzero or true all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro
any(A) % Tests if any elements are nonzero or true any(A) % Testa se algum elemento é diferente de zero ou verdadeiro
isequal(A, B) % Tests equality of two arrays isequal(A, B) % Testa a igualdade de duas matrizes
numel(A) % Number of elements in matrix numel(A) % Número de elementos na matriz
triu(x) % Returns the upper triangular part of x triu(x) % Retorna a parte triangular superior de x
tril(x) % Returns the lower triangular part of x tril(x) % Retorna a parte triangular inferior de x
cross(A,B) % Returns the cross product of the vectors A and B cross(A,B) % Retorna o produto cruzado das matrizes A e B
dot(A,B) % Returns scalar product of two vectors (must have the same length) dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho)
transpose(A) % Returns the transpose of A transpose(A) % Retorna a matriz transposta de A
fliplr(A) % Flip matrix left to right fliplr(A) % Inverte a matriz da esquerda para a direita
flipud(A) % Flip matrix up to down flipud(A) % Inverte a matriz de cima para baixo
% Matrix Factorisations % Fatorações de Matrizes
[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix [L, U, P] = lu(A) % Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação
[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues [P, D] = eig(A) % Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores
[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order [U,S,V] = svd(X) % SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente
% Common vector functions % Funções Vetoriais Comuns
max % largest component max % Maior componente
min % smallest component min % Menor componente
length % length of a vector length % Tamanho do vetor
sort % sort in ascending order sort % Ordena em orcer ascendente
sum % sum of elements sum % Soma de elementos
prod % product of elements prod % Produto de elementos
mode % modal value mode % Valor modal
median % median value median % Valor mediano
mean % mean value mean % Valor médio
std % standard deviation std % Desvio padrão
perms(x) % list all permutations of elements of x perms(x) % Lista todas as permutações de elementos de x
% Classes % Classes
% Matlab can support object-oriented programming. % Matlab pode suportar programação orientada a objetos.
% Classes must be put in a file of the class name with a .m extension. % Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m
% To begin, we create a simple class to store GPS waypoints. % Para começar, criamos uma simples classe que armazena posições de GPS
% Begin WaypointClass.m % Início ClassePosicoesGPS.m
classdef WaypointClass % The class name. classdef ClassePosicoesGPS % O nome da classe.
properties % The properties of the class behave like Structures properties % As propriedades da classe comportam-se como estruturas
latitude latitude
longitude longitude
end end
methods methods
% This method that has the same name of the class is the constructor. % Este método que tem o mesmo nome da classe é o construtor.
function obj = WaypointClass(lat, lon) function obj = ClassePosicoesGPS(lat, lon)
obj.latitude = lat; obj.latitude = lat;
obj.longitude = lon; obj.longitude = lon;
end end
% Other functions that use the Waypoint object % Outras funções que usam os objetos de PosicoesGPS
function r = multiplyLatBy(obj, n) function r = multiplicarLatPor(obj, n)
r = n*[obj.latitude]; r = n*[obj.latitude];
end end
% If we want to add two Waypoint objects together without calling % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar
% a special function we can overload Matlab's arithmetic like so: % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira:
function r = plus(o1,o2) function r = plus(o1,o2)
r = WaypointClass([o1.latitude] +[o2.latitude], ... r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ...
[o1.longitude]+[o2.longitude]); [o1.longitude]+[o2.longitude]);
end end
end end
end end
% End WaypointClass.m % End ClassePosicoesGPS.m
% We can create an object of the class using the constructor % Podemos criar um objeto da classe usando o construtor
a = WaypointClass(45.0, 45.0) a = ClassePosicoesGPS(45.0, 45.0)
% Class properties behave exactly like Matlab Structures. % Propriedades da classe se comportam exatamente como estruturas Matlab
a.latitude = 70.0 a.latitude = 70.0
a.longitude = 25.0 a.longitude = 25.0
% Methods can be called in the same way as functions % Métodos podem ser chamados da mesma forma que funções
ans = multiplyLatBy(a,3) ans = multiplicarLatPor(a,3)
% The method can also be called using dot notation. In this case, the object % O método também pode ser chamado usando a notação de ponto. Neste caso,
% does not need to be passed to the method. % o objeto não precisa ser passado para o método.
ans = a.multiplyLatBy(a,1/3) ans = a.multiplicarLatPor(a,1/3)
% Matlab functions can be overloaded to handle objects. % Funções do Matlab podem ser sobrepostas para lidar com objetos.
% In the method above, we have overloaded how Matlab handles % No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de
% the addition of two Waypoint objects. % dois objetos PosicoesGPS.
b = WaypointClass(15.0, 32.0) b = ClassePosicoesGPS(15.0, 32.0)
c = a + b c = a + b
``` ```
## More on Matlab ## Mais sobre Matlab
* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) * O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) * O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)