Gerar matrizes a partir de funções f(i,j)
De GNU Octave
Ficha de Álgebra Linear e Geometria Analítica
Na ficha de Álgebra Linear e Geometria Analítica utilizam-se matrizes definidas com base numa função.
Exercício 1
As três matrizes A, B e C são 4x4.
Começamos por criar duas matrizes, uma LINHAS e uma COLUNAS com os índices linhas e colunas, que serão usadas como argumentos para funções.
>> x=0:3; y=0:3; >> [COLUNAS,LINHAS] = meshgrid(x,y) COLUNAS = 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 LINHAS = 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3
O nosso objetivo é criar as novas matrizes, aplicando uma função que vai buscar os valores às matrizes LINHAS e COLUNAS.
Vamos escrever 3 funções, de acordo com a respetiva definição:
function res = funA(i, j) if (i>j) res = -1; endif if (i == j) res = 0; endif if (i<j) res = 1; endif endfunction
function res = funB(i, j) if (i+j > 5) res = 1; endif if (i+j <= 5) res = 0; endif endfunction
function res = funC(i, j) res = (-1)^(i-j); endfunction
Para gerar a matriz A, teríamos que fazer:
>> A = arrayfun(@(a,b)funA(a,b),LINHAS,COLUNAS) A = 0 1 1 1 -1 0 1 1 -1 -1 0 1 -1 -1 -1 0
Para gerar a matriz B, teríamos que fazer:
>> B = arrayfun(@(a,b)funB(a,b),LINHAS,COLUNAS) B = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
Para gerar a matriz C, teríamos que fazer:
>> C = arrayfun(@(a,b)funC(a,b),LINHAS,COLUNAS) C = 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1