Documentos de Académico
Documentos de Profesional
Documentos de Cultura
- 55 -
16.
MATRICES DINMICAS
Los
procedimientos
empleados
para
vectores
dinmicos
pueden
ser
extendidos fcilmente par trabajar con matrices dinmicas, para ello
simplemente se reserva memoria adicional para las otras dimensiones. Por
ejemplo, en el siguiente segmento de cdigo se crea la matriz dinmica ma
con 10 filas y 20 columnas:
type tm= array of array of double;
var ma: tm;
begin
SetLength(ma,10,20);
Al igual que ocurre con los vectores dinmicos, en las matrices dinmicas
los primeros ndices son siempre 0, as el primer elemento de la matriz ma
es ma[0,0] y el ltimo ma[9,19]. A diferencia de las matrices estticas, las
matrices dinmicas pueden no ser rectangulares, es decir pueden tener
diferentes nmeros de elementos en cada una de sus filas. Por ejemplo en el
siguiente segmento de cdigo se crea, llena y muestra una matriz que tiene
una columna en la primera fila, dos en la segunda, tres en la tercera y as
sucesivamente hasta la vigsima fila:
type tmreal= array of array of real;
procedure TForm1.FormCreate(Sender:Tobject);
var ma: tmreal; i,j: byte;
begin
SetLength(ma,20);
for i:=0 to 19 do
SetLength(ma[i],i+1);
for i:=0 to 19 do
for j:=0 to i do ma[i,j]:=i+1;
Memo1.Lines.Clear;
for i:=0 to 19 do begin
Memo1.Lines.Append('');
for j:=0 to i do
Memo1.Lines[i]:=Memo1.Lines[i]+FloatToStr(ma[i,j])+' ';
end;
Para liberar la memoria se sigue empleando el procedimiento Finalize
(Finalize(Variable)):
16.1. Ejemplos
En los siguientes ejemplos las interfaces grficas de las aplicaciones no
tienen componentes nuevos con relacin a los del anterior tema, razn por la
cual no se darn mayores explicaciones con relacin a las mismas.
1.
- 56 -
Hernn Pearanda V.
MATRICES DINMICAS
- 57 -
- 58 -
Hernn Pearanda V.
end;
end.
El cdigo de la unidad principal (la unidad de la forma) donde se
modifican las propiedades de los componentes y se programan los evento
onClick de los ToolButton es el siguiente:
unit ufMulMat;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, Grids, ExtCtrls, ComCtrls, ToolWin, StdCtrls;
type
TForm1 = class(TForm)
ToolBar1: TToolBar;
StatusBar1: TStatusBar;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
StringGrid1: TStringGrid;
StringGrid2: TStringGrid;
StringGrid3: TStringGrid;
ImageList1: TImageList;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
ComboBox3: TComboBox;
ComboBox4: TComboBox;
ComboBox5: TComboBox;
ComboBox6: TComboBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure tb1Click(sender: TObject);
procedure tb2Click(sender: TObject);
procedure tb3Click(sender: TObject);
procedure tb4Click(sender: TObject);
end;
var
Form1: TForm1;
implementation
uses uDinamicos;
MATRICES DINMICAS
- 59 -
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var tb:tToolButton; bm:tBitmap; path:string; i:word;
const images: array [1..4] of string = ('Clear.bmp',
'Calculat.bmp','Retry.bmp','DoorOpen.bmp');
hints: array [1..4] of string = ('Borrar Matriz',
'Multiplicar Matrices','Generar Matriz','Salir de la aplicacin');
begin
Form1.Width:=700;
Form1.Height:=500;
Form1.Position:=poScreenCenter;
Form1.BorderStyle:=bsNone;
bm:=tBitmap.Create;
path:='C:\Archivos de programa\Archivos comunes\Borland Shared\'+
'Images\Buttons\';
for i:=1 to 4 do begin
bm.LoadFromFile(path+images[i]);
ImageList1.Add(bm,Nil);
ImageList1.Delete(i);
end;
bm.Free;
for i:=1 to 4 do begin
tb:=tToolButton.Create(ToolBar1);
tb.Hint:=hints[i];
tb.ImageIndex:=i-1;
tb.Cursor:=crHandPoint;
tb.Parent:=ToolBar1;
end;
ToolBar1.Images:=ImageList1;
ToolBar1.Buttons[0].OnClick:=tb1Click;
ToolBar1.Buttons[1].OnClick:=tb2Click;
ToolBar1.Buttons[2].OnClick:=tb3Click;
ToolBar1.Buttons[3].OnClick:=tb4Click;
Panel1.Align:=alLeft;
Panel1.Caption:='';
Panel1.Width:=Form1.ClientWidth div 2;
Panel2.Align:=alRight;
Panel2.Caption:='';
Panel2.Width:=Panel1.Width;
Panel3.Width:=Form1.ClientWidth;
Panel3.Height:=(Form1.ClientHeight-ToolBar1.Height-StatusBar1.Height)
div 2;
StatusBar1.SimplePanel:=True;
StatusBar1.SimpleText:='Multiplicacin de Matrices';
StatusBar1.AutoHint:=True;
Panel3.Align:=alBottom;
Panel4.Parent:=Panel1;
Panel4.Caption:='Matriz A';
Panel4.Alignment:=taLeftJustify;
Panel4.Align:=alTop;
Panel4.Height:=30;
- 60 -
Hernn Pearanda V.
Panel5.Parent:=Panel2;
Panel5.Caption:='Matriz B';
Panel5.Alignment:=taLeftJustify;
Panel5.Align:=alTop;
Panel5.Height:=30;
Panel6.Parent:=Panel3;
Panel6.Caption:='Matriz c';
Panel6.Alignment:=taLeftJustify;
Panel6.Align:=alTop;
Panel6.Height:=30;
Label1.Parent:=Panel4;
Label1.Caption:='Filas:';
Label1.Left:=70;
Label1.Top:=(Panel4.Height-Label1.Height) div 2;
Label2.Parent:=Panel4;
Label2.Caption:='Columnas:';
Label2.Left:=170;
Label2.Top:=Label1.Top;
Label3.Parent:=Panel5;
Label3.Caption:='Filas:';
Label3.Left:=70;
Label3.Top:=Label1.Top;
Label4.Parent:=Panel5;
Label4.Caption:='Columnas:';
Label4.Left:=170;
Label4.Top:=Label1.Top;
Label5.Parent:=Panel6;
Label5.Caption:='Filas:';
Label5.Left:=70;
Label5.Top:=Label1.Top;
Label6.Parent:=Panel6;
Label6.Caption:='Columnas:';
Label6.Left:=170;
Label6.Top:=Label1.Top;
ComboBox1.Parent:=Panel4;
ComboBox1.Width:=60;
for i:=1 to 500 do ComboBox1.Items.Append(IntToStr(i));
ComboBox1.ItemIndex:=0;
ComboBox1.Left:=Label1.Left+Label1.Width+5;
ComboBox1.Top:=(Panel4.Height-ComboBox1.ClientHeight) div 2;
ComboBox1.Style:=csDropDownList;
ComboBox2.Parent:=Panel4;
ComboBox2.Width:=60;
ComboBox2.Items.Assign(ComboBox1.Items);
ComboBox2.ItemIndex:=0;
ComboBox2.Left:=Label2.Left+Label2.Width+5;
ComboBox2.Top:=ComboBox1.Top;
ComboBox2.Style:=csDropDownList;
ComboBox3.Parent:=Panel5;
ComboBox3.Width:=60;
ComboBox3.Items.Assign(ComboBox1.Items);
MATRICES DINMICAS
ComboBox3.ItemIndex:=0;
ComboBox3.Left:=Label3.Left+Label3.Width+5;
ComboBox3.Top:=ComboBox1.Top;
ComboBox3.Style:=csDropDownList;
ComboBox4.Parent:=Panel5;
ComboBox4.Width:=60;
ComboBox4.Items.Assign(ComboBox1.Items);
ComboBox4.ItemIndex:=0;
ComboBox4.Left:=Label4.Left+Label4.Width+5;
ComboBox4.Top:=ComboBox1.Top;
ComboBox4.Style:=csDropDownList;
ComboBox5.Parent:=Panel6;
ComboBox5.Width:=60;
ComboBox5.Items.Assign(ComboBox1.Items);
ComboBox5.ItemIndex:=0;
ComboBox5.Left:=Label5.Left+Label5.Width+5;
ComboBox5.Top:=ComboBox1.Top;
ComboBox5.Style:=csDropDownList;
ComboBox6.Parent:=Panel6;
ComboBox6.Width:=60;
ComboBox6.Items.Assign(ComboBox1.Items);
ComboBox6.ItemIndex:=0;
ComboBox6.Left:=Label6.Left+Label6.Width+5;
ComboBox6.Top:=ComboBox1.Top;
ComboBox6.Style:=csDropDownList;
StringGrid1.Parent:=Panel1;
StringGrid1.FixedCols:=0;
StringGrid1.FixedRows:=0;
StringGrid1.Options:=StringGrid1.Options+[goThumbTracking,goEditing];
StringGrid1.DefaultColWidth:=60;
StringGrid1.RowCount:=1;
StringGrid1.ColCount:=1;
StringGrid1.Align:=alClient;
StringGrid1.Hint:='Matriz A';
StringGrid2.Parent:=Panel2;
StringGrid2.FixedCols:=0;
StringGrid2.FixedRows:=0;
StringGrid2.Options:=StringGrid1.Options+[goThumbTracking,goEditing];
StringGrid2.DefaultColWidth:=60;
StringGrid2.RowCount:=1;
StringGrid2.ColCount:=1;
StringGrid2.Align:=alClient;
StringGrid2.Hint:='Matriz B';
StringGrid3.Parent:=Panel3;
StringGrid3.FixedCols:=0;
StringGrid3.FixedRows:=0;
StringGrid3.Options:=StringGrid1.Options+[goThumbTracking,goEditing];
StringGrid3.DefaultColWidth:=60;
StringGrid3.RowCount:=1;
StringGrid3.ColCount:=1;
StringGrid3.Align:=alClient;
StringGrid3.Hint:='Matriz C';
end;
- 61 -
- 62 -
Hernn Pearanda V.
MATRICES DINMICAS
- 63 -
ComboBox5.ItemIndex:=Length(a)-1;
ComboBox6.ItemIndex:=Length(b[0])-1;
Finalize(a); Finalize(b); Finalize(c);
end;
procedure TForm1.tb4Click(sender: TObject);
begin
BorrarStringGrid(StringGrid1);
BorrarStringGrid(StringGrid2);
BorrarStringGrid(StringGrid3);
end;
end.
En ejecucin la aplicacin tiene la apariencia que se muestra en la
figura de la anterior pgina.
2.
15 8 1
17
14 7 5
13 6 4
3
12 10
9 2
11
15 8 1
17
16 14 7 5
20 13 6 4
3
19 12 10
9 2
18 11
15 8 1 24 17
16 14 7 5 23
22 20 13 6 4
3 21 19 12 10
9 2 25 18 11
- 64 -
Hernn Pearanda V.
MATRICES DINMICAS
- 65 -
end.
El cdigo de los eventos onCreate
ComboBox1 son los siguientes:
de
la
forma
onChange
del
- 66 -
Hernn Pearanda V.
end;
En ejecucin la aplicacin tiene la apariencia que se muestra en la
siguiente figura:
3.
MATRICES DINMICAS
function GenerarMatriz():tmInteger;
procedure IntercambiarFilas(a:tmInteger;f1,f2:word);
procedure IntercambiarColumnas(a:tmInteger;c1,c2:word);
implementation
uses unit1;
function LeerMatriz(s:tStringGrid):tmInteger;
var nf,nc,i,j: word; a:tmInteger;
begin
nf:=s.RowCount;
nc:=s.ColCount;
SetLength(a,nf,nc);
for i:=0 to nf-1 do
for j:=0 to nc-1 do
a[i,j]:=StrToInt(s.Cells[j,i]);
result:=a;
end;
procedure MostrarMatriz(a:tmInteger; s:tStringGrid);
var nf,nc,i,j: word;
begin
nf:=Length(a);
nc:=Length(a[0]);
s.RowCount:=nf;
s.ColCount:=nc;
for i:=0 to nf-1 do
for j:=0 to nc-1 do
s.Cells[j,i]:=IntToStr(a[i,j]);
end;
function MatrizAleatoria(nf,nc:word; li,ls:integer):tmInteger;
var i,j: word; d:integer; a:tmInteger;
begin
randomize;
SetLength(a,nf,nc);
d:=ls-li+1;
for i:=0 to nf-1 do
for j:=0 to nc-1 do
a[i,j]:=random(d)+li;
result:=a;
end;
function GenerarMatriz():tmInteger;
var Label1,Label2,Label3,Label4:tLabel;
Edit1,Edit2,Edit3,Edit4:tEdit;
BitBtn1,BitBtn2:tBitBtn;
Form2:tForm;
li,ls:integer;
nf,nc:word;
begin
try
Form2:=TForm.Create(Form1);
Form2.BorderStyle:=bsDialog;
Form2.Position:=poScreenCenter;
Form2.Caption:='Generar nmeros enteros';
- 67 -
- 68 -
Hernn Pearanda V.
Label1:=TLabel.Create(Form2);
Label1.Parent:=Form2;
Label1.Left:=50;
Label1.Top:=20;
Label1.Caption:='Lmite inferior:';
Edit1:=TEdit.Create(Form2);
Edit1.Parent:=Form2;
Edit1.Left:=Label1.Left+Label1.Width+5;
Edit1.Top:=Label1.Top-(Edit1.Height-Label1.Height) div 2;
Edit1.Text:='1';
Label2:=tLabel.Create(Form2);
Label2.Parent:=Form2;
Label2.Caption:='Lmite superior:';
Label2.Left:=Label1.Left+Label1.Width-Label2.Width;
Label2.Top:=Label1.Top+Label1.Height+20;
Edit2:=tEdit.Create(Form2);
Edit2.Parent:=Form2;
Edit2.Left:=Edit1.Left;
Edit2.Top:=Label2.Top-(Edit2.Height-Label2.Height) div 2;
Edit2.Text:='100';
Label3:=tLabel.Create(Form2);
Label3.Parent:=Form2;
Label3.Caption:='Nmero de filas:';
Label3.Left:=Label1.Left+Label1.Width-Label3.Width;
Label3.Top:=Label2.Top+Label2.Height+20;
Edit3:=tEdit.Create(Form2);
Edit3.Parent:=Form2;
Edit3.Left:=Edit1.Left;
Edit3.Top:=Label3.Top-(Edit3.Height-Label3.Height) div 2;
Edit3.Text:='6';
label4:=tLabel.Create(Form2);
Label4.Parent:=Form2;
Label4.Caption:='Nmero de columnas:';
Label4.Top:=Label3.Top+Label3.Height+20;
Label4.Left:=Label1.Left+Label1.Width-Label4.Width;
Edit4:=TEdit.Create(Form2);
Edit4.Parent:=Form2;
Edit4.Left:=Edit1.Left;
Edit4.Top:=Label4.Top-(Edit4.Height-Label4.Height) div 2;
Edit4.Text:='7';
Form2.ClientWidth:=Edit4.Left+Edit4.Width+20;
BitBtn1:=tBitBtn.Create(Form2);
BitBtn1.Parent:=Form2;
BitBtn1.Kind:=bkOk;
BitBtn1.Cursor:=crHandPoint;
BitBtn1.Width:=80;
BitBtn1.Caption:='&Aceptar';
BitBtn1.Top:=Edit4.Top+Edit4.Height+20;
MATRICES DINMICAS
BitBtn1.Left:=(Form2.ClientWidth-(BitBtn1.Width*2+30)) div 2;
BitBtn2:=tBitBtn.Create(Form2);
BitBtn2.Parent:=Form2;
BitBtn2.Kind:=bkCancel;
BitBtn2.Cursor:=crHandPoint;
BitBtn2.Width:=BitBtn1.Width;
BitBtn2.Caption:='&Cancelar';
BitBtn2.Top:=BitBtn1.Top;
BitBtn2.Left:=BitBtn1.Left+BitBtn1.Width+30;
Form2.ClientHeight:=BitBtn1.Top+BitBtn1.Height+20;
if Form2.ShowModal=mrOk then begin
li:=StrToInt(Edit1.Text);
ls:=StrToInt(Edit2.Text);
nf:=StrToInt(Edit3.Text);
nc:=StrToInt(Edit4.Text);
result:=MatrizAleatoria(nf,nc,li,ls); end
else
result:=nil;
finally
Form2.Free;
end;
end;
procedure IntercambiarFilas(a:tmInteger;f1,f2:word);
var nf,nc,j: word; aux:integer;
begin
nf:=Length(a);
nc:=Length(a[0]);
if f1>nf then raise EInvalidArgument.Create(
'En la matriz no existe la fila '+IntToStr(f1));
if f2>nf then raise EInvalidArgument.Create(
'En la matriz no existe la fila '+IntToStr(f2));
for j:=0 to nc-1 do begin
aux:=a[f1,j];
a[f1,j]:=a[f2,j];
a[f2,j]:=aux;
end;
end;
procedure IntercambiarColumnas(a:tmInteger;c1,c2:word);
var nf,nc,i:word; aux:integer;
begin
nf:=Length(a);
nc:=Length(a[0]);
if c1>nc then raise EInvalidArgument.Create(
'En la matriz no existe la columna: '+IntToStr(c1));
if c2>nc then raise EInvalidArgument.Create(
'En la matriz no existe la columna: '+IntToStr(c2));
for i:=0 to nf-1 do begin
aux:=a[i,c1];
a[i,c1]:=a[i,c2];
a[i,c2]:=aux;
end;
end;
- 69 -
- 70 -
Hernn Pearanda V.
end.
Y los eventos escritos en la unidad principal (el de la forma Form1) son:
uses Unit2;
procedure TForm1.FormCreate(Sender: TObject);
var i: word;
begin
Form1.Caption:='Intercambiar Filas y Columnas';
Form1.BorderStyle:=bsDialog;
Form1.Position:=poScreenCenter;
Panel1.Caption:='';
Panel1.Align:=alTop;
Panel1.Height:=40;
Panel1.BevelInner:=bvLowered;
BitBtn1.Parent:=Panel1;
BitBtn1.Width:=100;
BitBtn1.NumGlyphs:=2;
BitBtn1.Cursor:=crHandPoint;
BitBtn1.Kind:=bkRetry;
BitBtn1.Caption:='&Generar';
BitBtn1.Left:=20;
BitBtn1.Top:=(Panel1.Height-BitBtn1.Height) div 2;
RadioGroup1.Parent:=Panel1;
RadioGroup1.Color:=Panel1.Color;
RadioGroup1.Columns:=2;
RadioGroup1.Width:=150;
RadioGroup1.Height:=30;
RadioGroup1.Caption:='Intercambiar:';
RadioGroup1.Items.Add('Filas');
RadioGroup1.Items.Add('Columnas');
RadioGroup1.Left:=BitBtn1.Left+BitBtn1.Width+20;
RadioGroup1.Top:=(Panel1.Height-RadioGroup1.Height) div 2;
RadioGroup1.ItemIndex:=0;
Label1.Parent:=Panel1;
Label1.Transparent:=True;
Label1.Alignment:=taRightJustify;
Label1.Caption:='Fila 1:';
Label1.Left:=RadioGroup1.Left+RadioGroup1.Width+40;
Label1.Top:=(Panel1.Height-Label1.Height) div 2;
ComboBox1.Width:=40;
ComboBox1.Style:=csDropDownList;
ComboBox1.Cursor:=crHandPoint;
ComboBox1.Items.Clear;
for i:=1 to 100 do
ComboBox1.Items.Append(IntToStr(i));
ComboBox1.Top:=(Panel1.Height-ComboBox1.Height) div 2;
ComboBox1.Left:=Label1.Left+Label1.Width+5;
ComboBox1.ItemIndex:=2;
Label2.Parent:=Panel1;
MATRICES DINMICAS
Label2.Transparent:=True;
Label2.Alignment:=taRightJustify;
Label2.Caption:='Fila 2:';
Label2.Left:=ComboBox1.Left+ComboBox1.Width+40;
Label2.Top:=Label1.Top;
ComboBox2.Width:=40;
ComboBox2.Style:=csDropDownList;
ComboBox2.Cursor:=crHandPoint;
ComboBox2.Items.Assign(ComboBox1.Items);
ComboBox2.Top:= ComboBox1.Top;
ComboBox2.Left:=Label2.Left+Label2.Width+5;
ComboBox2.ItemIndex:=4;
BitBtn2.Parent:=Panel1;
BitBtn2.Width:=100;
BitBtn2.NumGlyphs:=2;
BitBtn2.Cursor:=crHandPoint;
BitBtn2.Kind:=bkOk;
BitBtn2.Cursor:=crHandPoint;
BitBtn2.Caption:='&Intercambiar';
BitBtn2.Left:=ComboBox2.Left+ComboBox2.Width+30;
BitBtn2.Top:=(Panel1.Height-BitBtn2.Height) div 2;
Panel2.Caption:='';
Panel2.Align:=alLeft;
Panel2.Width:=Form1.ClientWidth;
StringGrid1.Parent:=Panel2;
StringGrid1.Align:=alClient;
StringGrid1.FixedCols:=0;
StringGrid1.FixedRows:=0;
StringGrid1.RowCount:=ComboBox1.ItemIndex+1;
StringGrid1.ColCount:=ComboBox2.ItemIndex+1;
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
var a:tmInteger;
begin
a:=GenerarMatriz();
if a<>nil then begin
MostrarMatriz(a,StringGrid1);
Finalize(a);
end;
end;
procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
if RadioGroup1.ItemIndex=0 then begin
Label1.Caption:='Fila 1:';
Label2.Caption:='Fila 2:'; end
else begin
Label1.Caption:='Columna 1:';
Label2.Caption:='Columna 2:';
end;
end;
- 71 -
- 72 -
Hernn Pearanda V.
MATRICES DINMICAS
- 73 -
16.2. Ejercicios
1.
Cree una aplicacin con dos paneles, un StringGrid, dos Label, dos
ComboBox y un BitBtn. Escriba un mdulo que empleando vectores
dinmicos cree una matriz de nmeros enteros aleatorios comprendidos
entre -1000 y 1000 y otro que muestre los elementos de una matriz de
nmeros enteros en un StringGrid, con los nmeros de fila y columna en
la primera columna y fila del StringGrid. En el evento onCreate de la
aplicacin haga que el primer panel est alineado en la parte superior
de la forma y tenga 40 puntos de alto, que el segundo panel est
alineado en toda la forma, que el StrinGrid pertenezca al Panel2, est
alineado en todo el panel, tenga tres filas y tres columnas, que se
actualice a medida que se mueven las barras de desplazamiento; que los
Label pertenezcan al Panel1, tengan los ttulos Filas: y Columnas:,
sean transparentes, estn ubicados a 13 puntos de la parte superior y
30 y 130 puntos de la izquierda; que los ComboBox pertenezcan al
Panel1, tengan 60 puntos de ancho, estn ubicados a 10 puntos de la
parte superior y a 5 puntos a la derecha de los Label, que su lista
sean los nmeros del 2 al 100 y que est seleccionado el nmero 2; que
el BitBtn pertenezca al panel1, tenga la figura Calculat.bmp, el
ttulo Generar y que al hacer clic sobre el mismo se genere y muestre
una matriz aleatoria con el nmero de filas y columnas establecidos en
los ComboBox.
2.
- 74 -
Hernn Pearanda V.
4.
MATRICES DINMICAS
- 75 -
de Pascal son: 1;
1,6,15,20,15,6,1 ).
1,1;
1,2,1;
1,3,3,1;
1,4,6,4,1;
1,5,10,10,5,1;
5.
6.
9 10 11 12 9 7 11 15
13 14 15 16 13 14 12 16
Elabore una aplicacin que empleando vectores dinmicos lleve a cabo
dicha tarea.