Gravação e leitura de arquivos em disco e

geração de números com semente variável

Routo Terada

> restart;SAIDA:=fopen(sai,WRITE); primeiro, abrir arquivo sai para WRITE

SAIDA := 0

> fprintf(SAIDA, `Este arquivo foi gravado para testar`);

^^^ note o acento grave aqui

36

^^^^ isto é só o comprimento da string acima

> fclose(SAIDA); fechar arquivo sai após gravar

conteúdo do arquivo sai é:

Este arquivo foi gravado para testar

Saída para arquivo em disco - gravação

> restart; SAIDA:= fopen(sai2, WRITE);

SAIDA := 0

> x:= -123.456: printf(` x = %+08.2f \n`, x); total de 8 posições

x = -0123.46

> fprintf(SAIDA, ` x = %+08.2f \n`, x); destrói arquivo anterior!

15

> x:= 123.456: printf(` x= %f \n`, x);

x= 123.456000

> fprintf(SAIDA, ` x = %f \n`, x);

17

> str:= `marte e lua`: printf(` str= %s \n`, str);

str= marte e lua

> fprintf(SAIDA, ` str = %s \n`, str);

20

> fclose(SAIDA);

conteúdo do arquivo sai2 :

x = -0123.45
x = 123.456
str = marte e lua

Entrada de arquivo em disco - leitura

> restart;
Primeiro gravar arquivo cahamado entra1 que vai ser lido a seguir.

> SAIDA:= fopen(entra1, WRITE);
x:=12.3456: y:=78.9012: z:=45.67: t:=1.1:
fprintf(SAIDA, `%7.4f %7.4f \n %5.2f \n %3.1f`, x,y,z,t);
fclose(SAIDA);

SAIDA := 0

29

conteúdo do arquivo entra1 em disco:

12.3456 78.9012
45.67
1.1

> ENTRA:= fopen(entra1, READ);
lis:=fscanf(ENTRA,`%f %f`);
le uma lista de valores

ENTRA := 0

lis := [12.3456, 78.9012]

> lis[1]+11;

23.3456

> lista2:=fscanf(ENTRA,`%f`);

lista2 := [45.67]

> fclose(ENTRA);

Geração de números aleatórios alterando _seed

> gera:=rand(1..52); gera um número entre 1 e 52

gera := proc () local t; global _seed; _seed := ire...
gera := proc () local t; global _seed; _seed := ire...
gera := proc () local t; global _seed; _seed := ire...
gera := proc () local t; global _seed; _seed := ire...
gera := proc () local t; global _seed; _seed := ire...

> gera(); gera(); cada chamada gera um outro número

42

43

> lis:=gera();

lis := 18

> for j in [1,2,3,4] do

> outro:=gera(); lis:=[outro,op(lis)]

> od;

outro := 8

lis := [8, 18]

outro := 29

lis := [29, 8, 18]

outro := 15

lis := [15, 29, 8, 18]

outro := 50

lis := [50, 15, 29, 8, 18]

> _seed:= 13; mudança da semente chamada _seed

_seed := 13

> lis:=gera(); geração começa com nova semente

> for j in [1,2,3,4] do

> outro:=gera(); lis:=[outro,op(lis)]

> od;

lis := 25

outro := 15

lis := [15, 25]

outro := 2

lis := [2, 15, 25]

outro := 22

lis := [22, 2, 15, 25]

outro := 6

lis := [6, 22, 2, 15, 25]

> _seed:=1313: geração de float entre 0 e 1

> for j in [1,2,3,4,5] do

> printf(`\n %6.5f `,gera()/52.0);

> od;

.40385

.73077

.75000

.88462

.23077

Exercícios:

(1) Definir um valor arbitrário de _seed e depois gerar 6 números pseudo aleatórios usando gera().

(2) Alterar _seed para outro valor e gerar de novo 6 números; verificar que os números são diferentes.

GRÁFICOS

Gráficos 2D

> restart;plot([t,t^2,t=1.2..10.88],thickness=2);
# funcao parametrizada -
# lista com [eixo x, eixo y, variacao de t]

[Maple Plot]

Exercício : traçar um gráfico de x ao cubo no intervalo de 1 a 12.

Mais de um gráfico

> restart;plot([x-x^3.3/2,sin(x)],x=0..1,linestyle=[2,3],
thickness=2,color=[red,blue]);

[Maple Plot]

> plot([t,2*t*sin(t/4),t=0..8*Pi],thickness=2,color=brown);

[Maple Plot]

> plot(x^2*exp(-x),x=0..10,thickness=2);

[Maple Plot]

> plot([[5,5],[6.4,6.8],[7,8],[9,20]],thickness=2);

[Maple Plot]

> plot(sin(x)/x,x=-2*Pi..2*Pi,thickness=2,
title=`Gráfico do Seno()`,labels=[`Tempo`,`Y `],axes=boxed);

[Maple Plot]

Gráficos 3D

> plot3d(sin(4*x+y),x=-1..1,y=-1..1,axes=boxed,thickness=1);

[Maple Plot]

> plot3d(-x^3+y^3,x=0..5,y=0..5,axes=boxed,
labels=[`Eixo x`,`tempo`,`Z `]);

[Maple Plot]

Mais de um gráfico

> plot3d({sin(x*y), 2*x},
x=-2*Pi..2*Pi,y=-Pi..Pi,axes=boxed);

[Maple Plot]

Quatro gráficos

> c1:= [cos(x)-2*cos(0.4*y),sin(x)-2*sin(0.4*y),y]:
c2:= [cos(x)+2*cos(0.4*y),sin(x)+2*sin(0.4*y),y]:
c3:= [cos(x)+2*sin(0.4*y),sin(x)-2*cos(0.4*y),y]:
c4:= [cos(x)-2*sin(0.4*y),sin(x)+2*cos(0.4*y),y]:
plot3d({c1,c2,c3,c4},x=0..2*Pi,y=0..10,
grid=[25,15],style=patch,axes=boxed);

[Maple Plot]

Com variação de cor

> plot3d({c1,c2,c3,c4},x=0..2*Pi,y=0..10,grid=[25,15],
style=patch,color=sin(x),axes=boxed);

[Maple Plot]

Exercício : Traçar um gráfico 3D de x*cos(x)+y*cos(y) para x e y no intervalo de -Pi a +Pi

MATRIZES E VETORES

> restart;
with(linalg); # carrega o pacote linalg com as
# funções listadas a seguir

Warning, the protected names norm and trace have been redefined and unprotected

[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...
[BlockDiagonal, GramSchmidt, JordanBlock, LUdecomp,...

Para criar uma matriz 4 por 2

> M := matrix(4,2,[12.2,15.5,-28.8,21.1,35.12,36.0,4.,4.9]);

M := matrix([[12.2, 15.5], [-28.8, 21.1], [35.12, 3...

> M2 := addcol(M,1,2,5);

Somar à coluna 2 da matriz M a coluna 1 multiplicada por 5

M2 := matrix([[12.2, 76.5], [-28.8, -122.9], [35.12...

Somar à linha 4 de M2 a linha 2 multiplicada por 1/2

> M3 := addrow(M2,2,4,1/2);

M3 := matrix([[12.2, 76.5], [-28.8, -122.9], [35.12...

Exercício:

Definir uma matriz A de 3 linhas e 4 colunas. Depois somar a linha 1 à linha 2 multiplicado por -1 .

col(mat,n) para extrair a enésima coluna da matriz mat.

row(mat,n) para extrair a enésima linha da matriz mat.

> A := matrix(4,4,[-14.4,15.63,1.0,19,21.23,23,26.27,-25.4,
-35.19,33,-31.5,38.8,48,40.13,47,41]);

A := matrix([[-14.4, 15.63, 1.0, 19], [21.23, 23, 2...

> col(A,3); # extrai a coluna 3 da matriz A

vector([1.0, 26.27, -31.5, 47])

> row(A,1);

vector([-14.4, 15.63, 1.0, 19])

Para calcular matriz adjunta

> adjoint(A); # calcula a matriz adjunta de A

matrix([[-137790.4771, -5001.8360, 34040.3092, 2854...

Exercício : Calcular a matriz adjunta da matriz abaixo

M := MATRIX([[-21.2, 12, -2.5], [2.12, -2.4, -7.2],...

> A := 'A': # apagar a definição anterior de A.
A := matrix(3,3,[-1.2,11,-12.3,22,-24,-2.2,31.3,-34,-32]);

A := matrix([[-1.2, 11, -12.3], [22, -24, -2.2], [3...

> b := vector([4.222,-44.14,3.9]);

b := vector([4.222, -44.14, 3.9])

A seguir queremos resolver o sistema linear Ax=b pelo Algoritmo de Gauss-Jordan

Primeiro vamos concatenar as matrizes A e b.

> C := concat(A,b);

C := matrix([[-1.2, 11, -12.3, 4.222], [22, -24, -2...

Agora aplicamos o Algoritmo de Gauss-Jordan para resolver o sistema linear

> solucao := gaussjord(C);

solucao := matrix([[1, 0, 0, -5.284350111], [0, 1, ...

A seguir podemos extrair o vetor x, tal que Ax = b.

> x := col(solucao,4);

x := vector([-5.284350111, -2.791751485, -2.3243940...

Podemos resolver o sistema usando linsolve(A,b) onde A e' uma matriz e b um vetor

> linsolve(A,b);

vector([-5.284350109, -2.791751483, -2.324393999])

mulcol(mat,ncol,expr) para multiplicar a coluna ncol da matriz mat pela expressão expr.

mulrow(mat,nlin,expr) par multiplicar a linha nlin da matriz mat pela expressão expr.

> A := 'A':

> A := array([[-1.1,12.0,1.5,12.3],[21,-2.1,2.93,2.71],[-3.7,3.2,3.1,3.04],
[4.3,4.87,4.5,44.5]]);

A := matrix([[-1.1, 12.0, 1.5, 12.3], [21, -2.1, 2....

> A1 := mulcol(A,3,1/5); # multiplica a coluna 3 de A por 1/5

A1 := matrix([[-1.1, 12.0, .3000000000, 12.3], [21,...

> A2 := mulrow(A1,2,5); # multiplica a linha 2 de A por 5

A2 := matrix([[-1.1, 12.0, .3000000000, 12.3], [105...

Exercício : Resolver M x=b para a matriz M e vetor b abaixo

b := VECTOR([4.222, -44.14, 3.9])

M := MATRIX([[-21.2, 12, -2.5], [2.12, -2.4, -7.2],...

Multiplicação de matriz por escalar

scalarmul(mat,expr) para multiplicar ( por escalar ) cada elemento da matriz mat pela expressão expr.

> A3 := scalarmul(A2,x^2); # multiplica a matriz A2 por x^2

A3 := matrix([[-1.1*x^2, 12.0*x^2, .3000000000*x^2,...

> AA := matrix(4,4,[]): # cria a matriz AA com elementos indefinidos

> for i from 1 to 4 do
for j from 1 to 4 do
AA[i,j] := subs(x=2, A3[i,j]):
od
od; # substitui x por 2 em todos os elementos da matriz A3 e
# atribui o resultado `a matriz AA

PRINT de matriz

> print(AA); # imprime a matriz AA

matrix([[-4.4, 48.0, 1.200000000, 49.2], [420, -42....

> map(diff,A3,x); # deriva A3 com relacao a x

matrix([[-2.2*x, 24.0*x, .6000000000*x, 24.6*x], [2...

Troca de linhas e colunas

swapcol(mat, i, j) troca as colunas i e j da matriz mat e mostra a matriz resultante.

swaprow(mat,i,j) troca as linhas i e j da matriz mat e mostra a matriz resultante.

> A4 := swaprow(A3,4,1); # troca as linhas 4 e 1 da matriz A3

A4 := matrix([[4.3*x^2, 4.87*x^2, .9000000000*x^2, ...

> A5 := swapcol(A4,4,1); # troca as linhas 4 e 1 da matriz A4

A5 := matrix([[44.5*x^2, 4.87*x^2, .9000000000*x^2,...

Soma de matrizes

> A6 := matadd(A3,A5); # soma as matrizes A3 e A5

A6 := matrix([[43.4*x^2, 16.87*x^2, 1.200000000*x^2...

Exercício : Somar as duas matrizes abaixo com matadd()

A := MATRIX([[-1.2, 11, -12.3], [22, -24, -2.2], [3...

M := MATRIX([[-21.2, 12, -2.5], [2.12, -2.4, -7.2],...

Matriz bloco diagonal

> A := 'A':

> A := matrix(2,2,[1.21,1.5,-2.7,2.4]);

A := matrix([[1.21, 1.5], [-2.7, 2.4]])

> B := 'B':

> B := matrix(3,3,[-1.29,1.3,-1.6,2.2,22.24,2.1,-3.4,-33,3.65]);

B := matrix([[-1.29, 1.3, -1.6], [2.2, 22.24, 2.1],...

> BlockDiagonal(A,B); # constrói a matriz bloco diagonalizada
# formada por A e B.

matrix([[1.21, 1.5, 0, 0, 0], [-2.7, 2.4, 0, 0, 0],...

Extensão de matriz

extend(mat, m, n, val) estende a matriz mat para uma matriz em que m linhas e n colunas

são acrescentadas a matriz mat. Às novas entradas na matriz mat são atribuidas o valor val.

> A := 'A':

> A := matrix(2,2,[1.95,11.2,-21,29]);

A := matrix([[1.95, 11.2], [-21, 29]])

> B := 'B':

> B2 := extend(A,2,2,0); # acrescenta 2 linhas e 2 colunas à
# matriz A com valor 0

B2 := matrix([[1.95, 11.2, 0, 0], [-21, 29, 0, 0], ...

Exercício : Acrescentar a quarta linha com valor -1 à matriz

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

Cópia de matriz para uma outra matriz

> B1 := 'B1':

> B1 := copyinto(A,B2,3,3); # copia a matriz A em B a partir
# da posição (3,3);

B1 := matrix([[1.95, 11.2, 0, 0], [-21, 29, 0, 0], ...

Remoção de linhas e colunas

> B2 := 'B2':

> B2 := delcols(B1,1..2); # remove as colunas de 1 a 2 da matriz B1

B2 := matrix([[0, 0], [0, 0], [1.95, 11.2], [-21, 2...

> B3 := 'B3':

> B3 := delrows(B2,2..3); # remove as linhas de 2 a 3 da matriz B2

B3 := matrix([[0, 0], [-21, 29]])

> B3 := copyinto(matrix(1,2,[12.2,11.7]),B3,1,1);
# copia a matriz 1 por 2, [12.2, 11.7],
# na matriz B3, a partir da posição (1,1)

B3 := matrix([[12.2, 11.7], [-21, 29]])

Determinante e multiplicação de matrizes

> detB3 := det(B3); # calcula o determinante de B3

detB3 := 599.5

> B4 := evalm(B3^(-1)); # calcula a inversa de B3

B4 := matrix([[.4837364470e-1, -.1951626355e-1], [....

> evalm(B3 &* B4); # verifica se o produto de B3 e B4 é
# a matriz identidade

matrix([[.9999999999, 0.], [0., 1.000000000]])

Exercício : Calcular o determinante e a inversa da matriz

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

Matriz de Hilbert

> hilbert(5); # gera a matriz de Hilbert 5x5

matrix([[1, 1/2, 1/3, 1/4, 1/5], [1/2, 1/3, 1/4, 1/...

Concatenação de matrizes

> A := 'A': B := 'B': C := 'C':

> A := matrix(2,2,[-11.3,-11,20,2.2]);

A := matrix([[-11.3, -11], [20, 2.2]])

> B := matrix(2,2,[11.6,12.9,22,-2.92]);

B := matrix([[11.6, 12.9], [22, -2.92]])

> C := stackmatrix(A,B); # concatena as duas matrizes verticalmente

C := matrix([[-11.3, -11], [20, 2.2], [11.6, 12.9],...

Matriz de Vandermonde e transposta de matriz

> A := 'A':

> A := vandermonde([-2,3.2,-2.3,4]);
# acha a matriz de Vandermonde associada à lista

A := matrix([[1, -2, 4, -8], [1, 3.2, 10.24, 32.768...

> B := 'B':

> B := transpose(A); # calcula a transposta de A

B := matrix([[1, 1, 1, 1], [-2, 3.2, -2.3, 4], [4, ...

Exercício : Calcular a transposta da matriz

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

Base de espaço vetorial

> A := 'A':

> A := matrix(5,5,[1,-2,2,1,-2,1,1,2,-2,-2,1,0,0,2,-1,0,0,0,-2,0,-2,1,0,1,2]);

A := matrix([[1, -2, 2, 1, -2], [1, 1, 2, -2, -2], ...

> colspace(A); # acha uma base para o espaço coluna de A

{vector([1, 0, 0, 0, -1/3]), vector([0, 1, 0, 0, 1/...

> rowspace(A); # acha uma base para o espaço linha de A

{vector([0, 0, 0, 1, 0]), vector([1, 0, 0, 0, -1]),...

Posto (rank) e núcleo (kernel) de matriz

> rank(A); # calcula o posto de A

4

> nullspace(A); # acha uma base para o espaço nulo de A.
# É o mesmo que kernel(A)

{vector([2, 0, 1, 0, 2])}

> kernel(A);

{vector([2, 0, 1, 0, 2])}

> A := 'A':

> A := matrix(3,4,[11.3,19.3,19.12,10,23.4,28.3,22.3,23,41,4.91,47.1,41.71]);

A := matrix([[11.3, 19.3, 19.12, 10], [23.4, 28.3, ...

> rank(A); # acha o posto de A

3

Exercício : Calcular o posto e o núcleo da matriz abaixo

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

Algoritmo de Eliminação de Gauss

> gausselim(A); # aplica o método de eliminação de Gauss na matriz A

matrix([[41., 4.91, 47.1, 41.71], [0, 25.49770732, ...

Exercício : Aplicar o Algoritmo de Eliminação de Gauss à matriz abaixo

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

Bases e transformação de uma base para outra

> B1 := 'B1': B2 := 'B2': # a seguir as colunas de B1 formam uma base
# para o espaço R^4. As colunas de B2
# formam outra base.

> B1 := matrix(4,4,[1,0,0,2,2,2,2,1,1,1,2,1,2,1,2,1]);

B1 := matrix([[1, 0, 0, 2], [2, 2, 2, 1], [1, 1, 2,...

> B2 := matrix(4,4,[2,0,1,0,1,0,2,1,2,2,0,2,1,2,0,2]);

B2 := matrix([[2, 0, 1, 0], [1, 0, 2, 1], [2, 2, 0,...

> v := vector([1,-1,5,-1]); # v é um vetor do R^4 com relação a base B1

v := vector([1, -1, 5, -1])

A seguir, como encontrar v em relação à base B2, aplicando Gauss-Jordan

> B1_B2 := concat(B1,B2);

B1_B2 := matrix([[1, 0, 0, 2, 2, 0, 1, 0], [2, 2, 2...

> r_B1_B2 := gaussjord(B1_B2); # aplica o método de Gauss-Jordan,
# assim obtemos a matriz de transformação
# da base B1 para B2

r_B1_B2 := matrix([[1, 0, 0, 0, -1, 0, 0, 0], [0, 1...

> trans := delcols(r_B1_B2,1..4); # elimina as colunas de 1 a 4
# para obter a matriz de transformação

trans := matrix([[-1, 0, 0, 0], [0, -2, 2, -1], [3/...

Agora para achar v na base B2 basta multiplicar trans por v.

> v_B2 := evalm(trans &* v);

v_B2 := vector([-1, 13, -9, 4])

Algoritmo de GramSchmidt para obter base ortonormal

> v1:= 'v1': v2:= 'v2' : v3 := 'v3':

> v1 := vector([-2.89,-1,-2]):

> v2 := vector([0,-1.81,2]):

> v3 := vector([1,3,-2.44]):

Os vetores v1, v2 e v3 formam uma base para o espaço R^3.

Vamos aplicar o Algoritmo de GramSchmidt a este conjunto para obter uma base ortonormal.

> GramSchmidt([v1,v2,v3]);

[[-2.89, -1, -2], [-.4740153234, -1.974019143, 1.67...
[[-2.89, -1, -2], [-.4740153234, -1.974019143, 1.67...

Teorema de Laplace, cofator, determinante

> A := 'A':

> A := matrix(4,4,[12.2,10,-11,11.21,3,-1,-3,-1,-3,0,0,-1,2,-2,-3,1]);

A := matrix([[12.2, 10, -11, 11.21], [3, -1, -3, -1...

> cof := (-1)^(2+3) * det(minor(A,2,3));
# calcula o cofator do elemento (2,3) da matriz A

cof := -52.86

> detLaplace := sum('(-1)^(1+i)*det(minor(A,1,i))*A[1,i]', 'i' = 1..4);
# Aplica o Teorema de Laplace para calcular o determinante de A

detLaplace := 417.29

> detMaple := det(A); # calcula o determinante de A usando a função det()

detMaple := 417.29

Polinômio e matriz característica; autovetor e autovalor

> A := 'A': C := 'C':

> A := matrix(3,3,[14,-13.9,14.2,1,-3,1,-1,-1,-5]);

A := matrix([[14, -13.9, 14.2], [1, -3, 1], [-1, -1...

> C := charmat(A,lambda); # acha a matriz característica de A

C := matrix([[lambda-14, 13.9, -14.2], [-1, lambda+...

> Eq := det(C) = 0; # acha o polinômio característico de A

Eq := lambda^3-6*lambda^2-67.9*lambda-111.6 = 0

> solve(Eq); # resolve a equação anterior para achar os autovalores de A

-4., 12.27323862, -2.273238618

> eigenvals(A); # acha os autovalores de A

12.27323862, -2.273238618, -4.

> eigenvects(A); # acha os autovetores associados a cada autovalor

[-4.000000000, 1, {vector([-1.000000001, -.13523131...
[-4.000000000, 1, {vector([-1.000000001, -.13523131...
[-4.000000000, 1, {vector([-1.000000001, -.13523131...

Notação: [ -2.273238619 ,1,{[ 2.267319902 , 1.313047608 , -1.313047608 ]}] significa que

-2.273238619 é o autovalor, 1 é a multiplicidade do autovalor e

[ ... ] são os autovetores associados a este autovalor.

Exercício : Calcular o polinômio característico e os autovalores da matriz abaixo

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

Forma Canônica de Jordan

> Digits:=20:
A := matrix(2,2,[1.1,1.2,22.3,0]);
jordA := jordan(A); # acha a forma canônica de Jordan da matriz A

A := matrix([[1.1, 1.2], [22.3, 0]])

jordA := matrix([[5.7521630116712029077, 0], [0, -4...

Outra forma de calcular Jordan

> jordA := jordan(A,'T'); # acha a forma canonica de jordan da matriz A.
# 'T' é usado para retornar a matriz de
# transição tal que T^(-1)AT = jordA

jordA := matrix([[5.7521630116712029077, 0], [0, -4...

> print(T); # imprime a matriz de transição

matrix([[.55286262644654340140, .447137373553456598...

> B := evalm(inverse(T) &* A &* T); # calcula o produto T^(-1)AT

B := matrix([[5.7521630116712029075, .1e-18], [-.3e...

> equal( jordA, B); # verifica se as matrizes jordA e B são
# iguais (ou quase iguais)

false

Decomposição LU

> A := matrix([[1,-2,3],[2,k,6],[-1,3,k-3]]);

A := matrix([[1, -2, 3], [2, k, 6], [-1, 3, k-3]])

> Decomposto := LUdecomp(A,L='baixo',U='cima',
det='determ',rank='posto');

Decomposto := matrix([[1, -2, 3], [0, k+4, 0], [0, ...

> posto;

3

> evalm(cima);

matrix([[1, -2, 3], [0, k+4, 0], [0, 0, k]])

> evalm(baixo);

matrix([[1, 0, 0], [2, 1, 0], [-1, 1/(k+4), 1]])

> map(normal,evalm(baixo &* cima));
# para verificar a decomposição

matrix([[1, -2, 3], [2, k, 6], [-1, 3, k-3]])

> determ;

(k+4)*k

Mesmo cálculo para k=3

> Decomp2:=LUdecomp(subs(k=3,op(A)),
L='baixo',U='cima',det='determ',rank='posto');

Decomp2 := matrix([[1, -2, 3], [0, 7, 0], [0, 0, 3]...

> determ;

21

Exercício : Calcular a decomposição LU da matriz abaixo

MATRIX([[-1.1, 2.2, -3.3], [2.3, -3.4, 4.5], [-5.6,...

**************************************************************************

fopen()

**************************************************************************

Function: open - Opens a file for unbuffered reading or writing

Calling Sequence:
open(name, mode)

Parameters:
name - the name of the file to be opened
mode - one of READ or WRITE

Description:

Examples:

> fd := open(testFile,WRITE);

fd := 0

> fprintf(fd,`This is a test\n`);

15

> close(fd);

**************************************************************************

fclose(),close

**************************************************************************

Function: fclose - Closes a buffered file

Function: close - Closes an unbuffered file or pipe

Function: process[pclose] - Closes a pipe to a process started with popen

Calling Sequence:
fclose(file ...)
close(file ...)
pclose(file ...)

Parameters:
file - one or more names or file descriptors of open files to be closed

Description:

Examples:

> fd := fopen(testFile,WRITE,BINARY);

fd := 0

> fprintf(fd,`This is a test\n`);

15

> fclose(fd);

**************************************************************************

fprintf(),sprintf,printf

**************************************************************************

Function: fprintf - Prints expressions to file or pipe based on a format string

Function: sprintf - Prints expressions to a string based on a format string

Function: printf - Prints expressions to default stream based on a format string

Calling Sequence:
fprintf(file, fmt, x1, ..., xn);
sprintf(fmt, x1, ...,xn);
printf(fmt, x1, ...,xn);

Parameters:
file - a file descriptor or file name
fmt - the output format specification
x1, ..., xn - the expressions to be formatted

Description:

Examples:

> printf(`%g %g %g\n`,123,123/456,123456789);

123 .269737 1.234568e+08

> printf(`%-2.5s:%2.5s:%2.5s\n`,M,Map,MapleV);

M :Map:Maple

> x := 23; y := -1/x;

x := 23

y := -1/23

> printf(`x=%+06.2f y=%+0*.*f y=%a y=%m y=%M\n`,x,6,2,y,y,y,y);

x=+23.00 y=-00.04 y=-1/23 y=#!"""#B y=

Error, (in fprintf) integer, string, or function call expected

> ### WARNING: sprintf now outputs strings; nprintf can be used if names are wanted
### WARNING: %x or %X format should be %y or %Y if used with floating point arguments
printf(`%a\n`,sprintf(`%o %x\n\n`,17129,17129));

Error, (in sprintf) integer, string, or function call expected

> ### WARNING: sprintf now outputs strings; nprintf can be used if names are wanted
str := sprintf(`x = %d, y = %g`,x,y);

Error, (in sprintf) integer, string, or function call expected

> length(str);

3

**************************************************************************

fscanf(),sscanf(),scanf

**************************************************************************

Function: fscanf - Parses expressions from a file or pipe based on a format string

Function: sscanf - Parses expressions from a string based on a format string

Function: scanf - Parses expressions from default input stream based on a format string

Calling Sequence:
fscanf(file, fmt)
sscanf(str, fmt)
scanf(fmt)

Parameters:
file - a file descriptor or file name
str - the string being scanned
fmt - the scanning format specification

Description:

Examples:

The result will be a list containing a floating-point value, two integers, a string, and another integer.

> ### WARNING: sscanf now returns a string for the %s format instead of a name
sscanf(`123.456E7 123.456E7`,`%g%d.%d %[Ee] %d`);

[.123456e10, 123, 456,

The result will contain two strings and a floating-point value.

> ### WARNING: sscanf now returns a string for the %s format instead of a name
sscanf(`123.456E7 123.456E7`,`%s %c%f`);

[

The result will contain three floating-point values.

> ### WARNING: sscanf now returns a string for the %s format instead of a name
sscanf(`X=123.4 Y=-27.9 Z=2.3E-5`,`X=%f Y=%f Z=%f`);

[123.4, -27.9, .23e-4]

> ### WARNING: sscanf now returns a string for the %s format instead of a name
sscanf(`25 1/(x^4+1) test`,`%d%a%s`);

[25, 1/(x^4+1),

**************************************************************************

plot()

**************************************************************************

Function: plot - create a 2-dimensional plot of functions

Calling Sequence:
plot(f, h, v)
plot(f, h, v,...)

Parameters:
f - function(s) to be plotted
h - horizontal range
v - vertical range (optional)

Description:

Examples:

> restart;plot(cos(x) + sin(x), x=0..Pi);
plot(tan(x), x=-Pi..Pi);
plot([sin(t), cos(t), t=-Pi..Pi]);
plot(sin(t),t);

[Maple Plot]

[Maple Plot]

[Maple Plot]

[Maple Plot]

since no domain is specified in last example, we use t=-10..10
Same four plots, but as procedures or operators

> plot(cos + sin, 0..Pi);
plot(tan, -Pi..Pi);
plot([sin, cos, -Pi..Pi]);
plot(sin);

[Maple Plot]

[Maple Plot]

[Maple Plot]

[Maple Plot]

for expressions having discontinuities one can do

> restart;plot(tan(x),x=-2*Pi..2*Pi,y=-4..4, discont=true);
plot( -1 + 2*Heaviside(x-1) , x = -1..2, discont = true );

[Maple Plot]

[Maple Plot]

multiple plots (in a set or list)

> restart;plot([sin(x), x-x^3/6], x=0..2, color=[red,blue], style=[point,line]);

[Maple Plot]

infinity plots

> restart;plot(sin(x), x=0..infinity);

[Maple Plot]

point plots

> restart;l := [[ n, sin(n)] $n=1..10];
### WARNING: the definition of the type `symbol` has changed'; see help page for details
plot(l, x=0..15, style=point,symbol=circle);

l := [[1, sin(1)], [2, sin(2)], [3, sin(3)], [4, si...
l := [[1, sin(1)], [2, sin(2)], [3, sin(3)], [4, si...

[Maple Plot]

some other plots

> s := t->100/(100+(t-Pi/2)^8): r := t -> s(t)*(2-sin(7*t)-cos(30*t)/2):
plot([r(t),t,t=-Pi/2..3/2*Pi],numpoints=2000,coords=polar,axes=none);
plot([x, tan(x), x=-Pi..Pi], -4..4, -5..5, tickmarks=[8,10]);

[Maple Plot]

[Maple Plot]

polar coordinates (with thickened curve)

> plot([sin(4*x),x,x=0..2*Pi],coords=polar,thickness=3);

[Maple Plot]

**************************************************************************

plot3d()

**************************************************************************

Function: plot3d - three-dimensional plotting

Calling Sequence:
plot3d(expr1, x=a..b, y=c..d)
plot3d(f, a..b, c..d)
plot3d([exprf,exprg,exprh], s=a..b, t=c..d)
plot3d([f,g,h], a..b, c..d)

Parameters:
f,g,h - function(s) to be plotted
expr1 - expression in x and y.
exprf,exprg,exprh - expressions in s and t.
a,b - real constants.
c,d - real constants, procedures or expressions in x
x,y,s,t - names

Description:

Examples:

> restart;plot3d(sin(x+y),x=-1..1,y=-1..1);
plot3d(binomial,0..5,0..5,grid=[10,10]);

[Maple Plot]

[Maple Plot]

can have alternate coordinate systems

> restart;plot3d((1.3)^x * sin(y),x=-1..2*Pi,y=0..Pi,coords=spherical,style=patch);
plot3d([1,x,y],x=0..2*Pi,y=0..2*Pi,coords=toroidal(10),scaling=constrained);
plot3d(sin(x*y),x=-Pi..Pi,y=-Pi..Pi,style=contour);

[Maple Plot]

[Maple Plot]

[Maple Plot]

can have variable endpoints in some cases

> restart;plot3d(sin(x*y),x=-Pi..Pi,y=-x..x);
p:= proc(x,y) if x^2 < y then cos(x*y) else x*sin(x*y) fi end:
h:= proc(x) x^2 end:
plot3d(p,-2..2,-1..h);
plot3d([x*sin(x)*cos(y),x*cos(x)*cos(y),x*sin(y)],x=0..2*Pi,y=0..Pi);
plot3d(x*exp(-x^2-y^2),x=-2..2,y=-2..2,grid=[49,49]);

[Maple Plot]

[Maple Plot]

[Maple Plot]

[Maple Plot]

can specify a color function (or procedure)

> plot3d(x*exp(-x^2-y^2),x=-2..2,y=-2..2,color=x);
plot3d(p,-2..2,-1..h,color=h);

[Maple Plot]

[Maple Plot]

multiple 3d plots can also be done

> plot3d({sin(x*y), x + 2*y},x=-Pi..Pi,y=-Pi..Pi);
c1:= [cos(x)-2*cos(0.4*y),sin(x)-2*sin(0.4*y),y]:
c2:= [cos(x)+2*cos(0.4*y),sin(x)+2*sin(0.4*y),y]:
c3:= [cos(x)+2*sin(0.4*y),sin(x)-2*cos(0.4*y),y]:
c4:= [cos(x)-2*sin(0.4*y),sin(x)+2*cos(0.4*y),y]:
plot3d({c1,c2,c3,c4},x=0..2*Pi,y=0..10,grid=[25,15],style=patch);
plot3d({c1,c2,c3,c4},x=0..2*Pi,y=0..10,grid=[25,15],style=patch,color=sin(x));

[Maple Plot]

[Maple Plot]

[Maple Plot]

**************************************************************************

linsolve

**************************************************************************

Function: linalg[linsolve] - solution of linear equations

Calling Sequence:
linsolve(A, b, 'r', v)
linsolve(A, B, 'r', v)

Parameters:
A - a matrix
b - a vector
B - a matrix
r - (optional) a name
v - (optional) a name

Description:

Examples:

> with(linalg):

Warning, the protected names norm and trace have been redefined and unprotected

> A := matrix( [[1,2],[1,3]] ):
b := vector( [1,-2]):
linsolve(A, b);

vector([7, -3])

> B := matrix( [[1,1],[-2,1]] ):
linsolve(A, B);

matrix([[7, 1], [-3, 0]])

> A := matrix( [[5,7],[0,0]] ):
b := vector( [3,0] ):
linsolve(A, b, 'r');

vector([3/5-7/5*_t[1], _t[1]])

> r;

1

> linsolve(A, b, 'r', v);

vector([3/5-7/5*v[1], v[1]])

> A := matrix([[5,7],[10,14]]);

A := matrix([[5, 7], [10, 14]])

> B := matrix([[3,0],[6,0]]);

B := matrix([[3, 0], [6, 0]])

> linsolve(A, B);

matrix([[3/5-7/5*_t[1][1], -7/5*_t[2][1]], [_t[1][1...

**************************************************************************

rand()

**************************************************************************

Function: rand - Random Number Generator

Calling Sequence:
rand()
rand(r)

Parameters:
r - (optional) an integer range or an integer

Description:

Examples:

> rand();

427419669081

> rand();

321110693270

> die := rand(1..6):
die();

4

> die();

6

**************************************************************************

solve()

**************************************************************************

Function: solve - Solve Equations

Calling Sequence:
solve(eqn, var)
solve(eqns, vars)

Parameters:
eqn - an equation or inequality
eqns - a set of equations or inequalities
var - (optional) a name (unknown to solve for)
vars - (optional) a set of names (unknowns to solve for)

Description:

floats functions identity ineqs linear
radical scalar series system

Examples:

> solve( f=m*a, a );

f/m

> solve( {f=m*a}, {a} );

{a = f/m}

> eq := x^4-5*x^2+6*x=2;

eq := x^4-5*x^2+6*x = 2

> solve(eq,x);

1, 1, -1+sqrt(3), -1-sqrt(3)

> sols := [solve(eq,x)];

sols := [1, 1, -1+sqrt(3), -1-sqrt(3)]

> sols[1];

1

> evalf(sols);

[1., 1., .732050808, -2.732050808]

> sols := {solve(eq,x)};

sols := {1, -1-sqrt(3), -1+sqrt(3)}

> sols[1];

1

> subs( x=sols[1], eq );

2 = 2

> eqns := {u+v+w=1, 3*u+v=3, u-2*v-w=0};

eqns := {u+v+w = 1, 3*u+v = 3, u-2*v-w = 0}

> solve(x^5-3*x^4+2*x^2-x+3,x);

RootOf(_Z^5-3*_Z^4+2*_Z^2-_Z+3,index = 1), RootOf(_...
RootOf(_Z^5-3*_Z^4+2*_Z^2-_Z+3,index = 1), RootOf(_...
RootOf(_Z^5-3*_Z^4+2*_Z^2-_Z+3,index = 1), RootOf(_...

> ### WARNING: allvalues now returns a list of symbolic values instead of a sequence of lists of numeric values
allvalues(%);

Error, (in allvalues) redundant option RootOf(_Z^5-3*_Z^4+2*_Z^2-_Z+3,index = 3)

Manipulating Solutions solve for u,v,w

> sols := solve( eqns );

sols := {w = -2/5, u = 4/5, v = 3/5}

check solutions

> subs( sols, eqns );

{1 = 1, 0 = 0, 3 = 3}

pick off one solution

> subs( sols, u );

4/5

assign all solutions

> assign( sols );
u;

4/5

Other Examples

> solve( cos(x)+y = 9, x );

Pi-arccos(y-9)

> solve( x^2+x>5, x );

RealRange(-infinity,Open(-1/2-1/2*sqrt(21))), RealR...

> solve( x^6-2*x^2+2*x, x );

0, RootOf(_Z^5-2*_Z+2,index = 1), RootOf(_Z^5-2*_Z+...
0, RootOf(_Z^5-2*_Z+2,index = 1), RootOf(_Z^5-2*_Z+...
0, RootOf(_Z^5-2*_Z+2,index = 1), RootOf(_Z^5-2*_Z+...

> solve( {x^2*y^2=0, x-y=1} );

{y = 0, x = 1}, {y = 0, x = 1}, {x = 0, y = -1}, {x...

> solve( {x^2*y^2=0, x-y=1, x<>0} );

{y = 0, x = 1}, {y = 0, x = 1}

> solve( {x^2*y^2-b, x^2-y^2-a}, {x,y} );

{y = RootOf(_Z^4+_Z^2*a-b), x = RootOf(_Z^2-RootOf(...

> _EnvAllSolutions := true:
solve( sin(x)=cos(x)-1, x );

-1/2*Pi+2*Pi*_Z1, 2*Pi*_Z2

**************************************************************************

>