You are on page 1of 16

Instruccin de asignacin (=) 3

Sintaxis Inicializacin de Matrices


Nombre_de_variable=expresin Mediante lneas explcitas
>> velocidad de reaccin = 40 >> B=[1 2 3 4
??? Undefined command/function 5 6 7 8
'velocidad'. 1 1 2 0
>> 5x=7 4 5 1 7]
??? 5x=7
| B=
Error: Unexpected MATLAB expression.
>>Alumno1=9; 1 2 3 4
5 6 7 8
Matrices 1 1 2 0
>> A=[1 2 3;4 5 6] 4 5 1 7
A=
1 2 3 Mediante el operador (:)
4 5 6 >> x=1:5
Fila x=
1 2 3 4 5
>> y=2:2:10
%aij=A(i,j)
y=
Columna 2 4 6 8 10
>> A(2,3)
ans = Sintaxis
6 Valor inical:Valor final (incrementar + 1)
>> A(1,3)=8; Valor inicial:incremento:valor final
>> A
A=
1 2 8 >> c=10:-1:1
4 5 6 c=
>> A(2,5)=9 10 9 8 7 6 5 4 3
A= 2 1
1 2 8 0 0 >> M=0:pi/2:6*pi;
4 5 6 0 9 >> P=B(2:4,3:4)

Vectores:
: Significa todo
>> x=[7 8 9]; a:b desde la fila a hasta la fila b
>> x(2)
ans = P=
8 7 8
>> y=[1;2;3]; 2 0
>> y(2) 1 7
ans =
2
>> y(3)
ans =
>> z=B(2:4,2) A=
z= 0 0 0
6 0 0 0
1 > x=[3,2]
5 x=
3 2
>> Z=B(:,2:4) >> A=zeros(x)
Z= A=
2 3 4 0 0
6 7 8 0 0
1 2 0 0 0
5 1 7 >> size (A)
ans =
Concatenando matrices 3 2
A B

>> A=zeros(size(C))
A=
0 0
A B 0 0
0 0
0 0
>> A=[1 2;3 4]; 0 0
>> B=[5 6;7 8]; >> B=ones(2,2)
>> C=[A B] B=
C= 1 1
1 2 5 6 1 1
3 4 7 8 >> b=ones(4)
>> D=[A;B] b=
D= 1 1 1 1
1 2 1 1 1 1
3 4 1 1 1 1
5 6 1 1 1 1
7 8 >> I=eye(3)
>> x=1:5; I=
>> y=2:2:10; 1 0 0
>> C=[x' y'] 0 1 0
C= 0 0 1
1 2
2 4
3 6
4 8
5 10

Mediante funciones especiales


>> A=zeros(2,3)
Mediante la funcin input Funcin fprintf
Sintaxis:
Sintaxis:
Fprintf(texto, listado de variables)
Nombre_de_variable=input(texto);

Contiene especificaciones
Ej: de formato
>> A=input('Ingrese la matriz A: ')
Ingrese la matriz A: [1 2;3 4] % e notacin cientfica
%f: notacin de punto fijo
A= %g: el ms corto entre %f y %e y
eliminando ceros no significativos.
1 2 >> x=8.5
2 4 x=
>> A=input('Ingrese la matriz A: '); 8.5000
Ingrese la matriz A: [1 2;3 4] >> fprintf('La nota obtenida en el
examen es %f',x)
Operaciones de Salida La nota obtenida en el examen es
>> 1.234567890123456789 8.500000>>
ans = >> fprintf('La nota obtenida en el
1.2346 examen es %e',x)
>>format short % 4 decimales La nota obtenida en el examen es
>>format long % 14 decimales 8.500000e+000>>
>>disp(x) % solo muestra el >> fprintf('La nota obtenida en el
contenido no asi el examen es %g\n',x)
nombre La nota obtenida en el examen es 8.5
1.2345678910234 >> a
>> format bank % 2 decimales a=
>> disp(x) 1.1235
1.23 >> fprintf('%5.2f\n',a)
>> format rat % Notacin 1.12
>> x=0.5 Fraccionaria >> fprintf('%.4e\n',a)
x= 1.1235e+000
>> fprintf('%7.2f\n %6.2f\n %5.2f\n
>> disp(pi) %4.2f\n',a,a,a,a)
355/113 1.12
>>help format 1.12
>>clock 1.12
ans = 1.12
1.0e+003 * >> fprintf('El valor de x es %.1e\ny el
2.0060 0.0080 0.0290 0.0110 valor de y es %g\n',x,y)
0.0560 0.0437 El valor de x es 3.6e-002
y el valor de y es 9
>> A=[1 2 3;4 5 6;7 8 9] OPERADORES ARITMTICOS
A= Operaciones entre escalares,
1 2 3 sean a, b escalares
4 5 6 o a+b(suma)
7 8 9 o a-b(resta)
>> fprintf('%g',A) o a*b(multiplicacin)
147258369>> o a/b(divisin de a entre b)
>> fprintf('%g\n',A) o a^b (potenciacin ab)
1
4 Jerarqua:
7
^ Primero
2
5
* / Izquierda a
8
derecha
3 + -
6
9
>> fprintf('%g %3.1f %g\n',A) >> 2^2-5
1 4.0 7 ans =
2 5.0 8 -1
3 6.0 9 >> 3^2-4*5/2+1
>> fprintf('%g%3.1f%g\n',A) ans =
14.07 0
25.08 x+ y
Ej:
36.09 n+w
a
>>(x+y)/(n+(w/a))
>>(x+y)/(n+w/a)
>>x+y/(n+w/a) No es igual!!!
a2 + b2
>>a^2 + b^2
>>(a^2) + (b^2)

Operadores Matriciales
Sean A, B matrices, n escalar no nulo.
o A+B (suma matricial)
o A-B (resta matricial)
o A*B (multiplicacin
matricial)
o A/B (A*B-1)
o A\B (A-1*B)
o A^n (A*A*A*A*...n veces
*A)
o A (Transpuesta de A)
Operaciones con Arreglos >> 5>3
Sean A, B matrices n un entero no ans =
nulo. 1
o A+B (aij+bij) >> 3>5
o A- B (aij-bij), ans =
o A.*B (aij*bij) 0
o A./B (aij/bij)
o A.\B (aij\bij)
o A.^n (aijn) >> A=[5 7 8];B=[4 7 9];
>> A<=B
Estas operaciones son elemento por ans =
elemento. 0 1 1
>> A=[8 1 2;3 5 6];B=[7,9,0;1,2,3];
>> x=[1 2 3]; >> A>B
>> y=x^2 ans =
??? Error using ==> mpower 1 0 1
Matrix must be square. 1 1 1
>> y=x.^2 >> A(2)==B(3)
y= ans =
1 4 9 0
>> d=x.*y >> V=[4 3 8];m=[3 2 7];
d= >> m==V-1
1 8 27 ans =
>> z=x+1 1 1 1
z=
2 3 4 Jerarqua
>> m=2*x 1. Operaciones aritmticas
m= 2. Operaciones relacionales
2 4 6
>> m=2.*x OPERACIONES LGICAS
m= o negacin (no)
2 4 6 o & conjucin (y)
o | disyuncin inclusiva (o)
OPERACIONES RELACIONALES Verdadero cualquier nmero no nulo
o > mayor que usualmente 1
o < menor que Falso cero
o >= mayor o igual que a b a a&b a | b xor(a,b)
o <= menor o igual que 0 0 1 0 0 0
o == igual a 0 1 1 0 1 1
o = distinto de 1 0 0 0 1 1
1 1 0 1 1 0
Expresin operaciones relacionales Jerarqua:
1 si es verdadero
0 si es falso. ~ Alta

Ej: & | Izquierda a


derecha
-1
>> ~1 0
ans = 1
0 >> x*y
>> ~0 ??? Error using ==> mtimes
ans = Inner matrix dimensions must agree.
1 >> x.*y
>> a=1;b=4;c=0; ans =
>> ~(b==c&b==4.4) 4
ans = 10
1 18
Ejemplos: >> x'*y
>> 1&0+3 ans =
ans = 32
1
>> 3>4&1 >> x.*y'
ans = ??? Error using ==> times
0 Matrix dimensions must agree.
>> 1|0&0 >> x*y'
ans = ans =
1 4 5 6
>> 0&0|1 8 10 12
ans = 12 15 18
1 >> x.*y'
>> x=[1 2 3]'; ??? Error using ==> times
>> y=[4 5 6]'; Matrix dimensions must agree.
>> x' >> x*2
ans = ans =
1 2 3 2
>> x+y 4
ans = 6
5 >> x./y
7 ans =
9 0.2500
>> x-y 0.4000
ans = 0.5000
-3 >> 2\x
-3 ans =
-3 0.5000
>> x+2 1.0000
ans = 1.5000
3 >> 2.\x
4 ans =
5 0.5000
>> x-2 1.0000
ans = 1.5000
>> x/2
ans =
0.5000
1.0000
1.5000
>> x^y
??? Error using ==> mpower FUNCIONES INTERNAS
At least one operand must be scalar. Trigonometric.
>> x.^y sin - Sine.
ans = sind - Sine of argument in degrees.
1 sinh - Hyperbolic sine.
32 asin - Inverse sine.
729 asind - Inverse sine, result in
>> x^2 degrees.
??? Error using ==> mpower asinh - Inverse hyperbolic sine.
Matrix must be square. cos - Cosine.
cosd - Cosine of argument in
degrees.
cosh - Hyperbolic cosine.
>> x.^2 acos - Inverse cosine.
ans = acosd - Inverse cosine, result in
1 degrees.
4 acosh - Inverse hyperbolic cosine.
9 tan - Tangent.
>> 2.^x tand - Tangent of argument in
ans = degrees.
2 tanh - Hyperbolic tangent.
4 atan - Inverse tangent.
8 atand - Inverse tangent, result in
degrees.
>> x+i*y
atan2 - Four quadrant inverse
ans =
tangent.
1.0000 + 4.0000i
atanh - Inverse hyperbolic tangent.
2.0000 + 5.0000i
sec - Secant.
3.0000 + 6.0000i
secd - Secant of argument in
>> (x+i*y)'
degrees.
ans =
sech - Hyperbolic secant.
1.0000 - 4.0000i 2.0000 - 5.0000i
asec - Inverse secant.
3.0000 - 6.0000i
asecd - Inverse secant, result in
degrees.
asech - Inverse hyperbolic secant.
csc - Cosecant.
cscd - Cosecant of argument in
degrees.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acscd - Inverse cosecant, result in cplxpair - Sort numbers into complex
degrees. conjugate pairs.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent. Rounding and remainder.
cotd - Cotangent of argument in fix - Round towards zero.
degrees. floor - Round towards minus
coth - Hyperbolic cotangent. infinity.
acot - Inverse cotangent. ceil - Round towards plus infinity.
acotd - Inverse cotangent, result in round - Round towards nearest
degrees. integer.
acoth - Inverse hyperbolic mod - Modulus (signed remainder
cotangent. after division).
rem - Remainder after division.
Exponential. sign - Signum.
exp - Exponential.
expm1 - Compute exp(x)-1 DATOS TIPOS CARACTER
accurately.
log - Natural logarithm. Alfanumricos:
log1p - Compute log(1+x) A,B,C,D..Z, a, b, c,.,z, 0, 1, 2,....,9
accurately. Tipo carcter:
log10 - Common (base 10) * , /, &, $
logarithm. Cadena (string)
log2 - Base 2 logarithm and dissect Para crear variables tipo cadena:
floating point number.
pow2 - Base 2 power and scale a) Sintaxis:
floating point number. Nombre_de_variable=Secuencia de
realpow - Power that will error out caractres
on complex result.
reallog - Natural logarithm of real >> a='Triunfar es'
number. a=
realsqrt - Square root of number Triunfar es
greater than or equal to zero.
sqrt - Square root.
nthroot - Real n-th root of real b) Sintaxis:
numbers. Nombre_de_variable=input(texto,s)
nextpow2 - Next higher power of 2.
>> b=input('Ingrese una frase:','s')
Complex. Ingrese una frase: hacer bien
abs - Absolute value. b=
angle - Phase angle. hacer bien
complex - Construct complex data >> a(4)
from real and imaginary parts. ans =
conj - Complex conjugate. u
imag - Complex imaginary part.
>> size (a)
real - Complex real part.
ans =
unwrap - Unwrap phase angle.
1 11
isreal - True for real array.
>> length(a) >> a='Materia';
ans = >> b='Alumno ';
11 >> c='Nota ';
>> c='1' >> e=[a;b;c]
c= e=
1 Materia
>> c-1 Alumno
ans = Nota
48 >> e(2,9)
>> c=1 ??? Index exceeds matrix dimensions.
c= >> e(2,9)
1 ??? Index exceeds matrix dimensions.
>> c-1 >> e(2,5)
ans = ans =
0 n
>> double('1') >> e(2,7)
ans = ans =
49
>> char('Materia','Alumno','Nota')
>> char(49)
ans =
ans =
Materia
1
Alumno
A B Nota
>> E=char('Primer parcial','Examen
Final');
>> M=char(B,E)
M=
A B
Materia
>>C=[A,B] Alumno
Nota
A Primer parcial
Examen Final
A
>> M=char(B,' ',E)
B
M=
B
Materia
Alumno
>>C=[A;B] Nota
>> d=[a,b,' lo que estas haciendo ahora']
d= Primer parcial
Triunfar es hacer bien lo que estas Examen Final
haciendo ahora >>x=5;
>> a='Materia';b='Alumno';c='Nota'; >>x=num2str(x)
>> e=[a;b;c] x=
??? Error using ==> vertcat 5
All rows in the bracketed expression must >>x-1
have the same ans=
number of columns. 52
>>x=str2num(x)
x=
5
>>x-1
ans=
4
Programacin Estructurada

Mtodo:
o Planteamiento del Problema
o Entrada/Salida
o Anlisis (analizar casos particulares/casos sencillos
o Creacin de un algoritmo
o Flujo grama
o Relato
o Pseudo cdigo
o Crear un cdigo (lenguaje de programacin)
o Probar el programa

La programacin estructurada trata de un conjunto de tcnicas para desarrollar


programas que sean fciles de escribir, verificar, leer y mantener (modificar y
actualizar). Estas tcnicas incluyen:
o Un nmero limitado de estructuras de control
a. Secuencia
b. Selectivas
c. Repetitivas
o Diseo descendente
o Composicin modular

Estructuras selectivas:

a. Seleccin simple (if/end)


b.

Para Matlab:
If <condicin>
Accin
End
c. Seleccin doble (if/else)

If condicin
accin1
else
accion2
end

Ej. Crear un programa en Matlab que pida al usario un nmero y que el programa
responda si el nmero es par o no.
%par.m
%Respnde si un nmero es par
a=input('Ingrese un nmero:');
r=rem(a,2);
if r==0 %no se debe poner el ;
fprintf('El nmero es par\n');
else
fprintf('El nmero no es par\n');
end

>> par
Ingrese un nmero:25
El nmero no es par
>> par
Ingrese un nmero:80
El nmero es par

d. Seleccin Mltiple MATLAB (switch)


switch <expresin>
case caso 1
accion 1
Expresion case caso 2
accion 2
= Case 1 = Case 2 = Case n otherwise .
.
.
Accin 1 Accin 2 Accin n Accin otro case caso n
accion n
otherwise
otra accion
end
Expresin no
= Caso 1

si Expresin no
Accin 1 = Caso 2

si Expresin no
Accin 2 = Caso n

si
Accin n Accin otro

MATLAB (if/elseif)
if <expression = caso 1>
accion 1
elseif expression = caso 2
accion 2
.
.
.
elseif expression = caso n
accion n
else
otra accion
end
Ej: Crear un programa en Matlab que resuelva la ecuacin ax+b=0, siendo a y b entradas
del usuario.
%ec.m
%Resuelva ax+b=0, con a y b entradas
%del usuario
fprintf('Resolviendo ax+b=0\n');
a=input('a=');
b=input('b=');
if a==0 & b==0
fprintf('Solucin indeterminada\n');
elseif a==0 & b~=0
fprintf ('Solucin Imposible\n');
else
fprintf('La solucin es x=%f\n',-b/a);
end
Corriendo el programa
>> ec
Resolviendo ax+b=0
a=1
b=1
La solucin es x=-1.000000
>> ec
Resolviendo ax+b=0
a=0
b=0
Solucin indeterminada
>> ec
Resolviendo ax+b=0
a=0
b=1
Solucin Imposible
>>
%ec2.m
%Resuelve ax+b=0
a=input('a=');
b=input('b=');
switch (abs(a) + abs(b))
case 0
fprintf('solucion indeterminada\n');
case b
fprintf('solucin imposible\n');
case -b
fprintf('solucin imposible\n');
otherwise
fprintf('La solucin es x=%g\n',-b/a);
end
Estructuras Repetivas (iterativas)

Bucle o Lazo: Es un conjunto de instrucciones que se repiten hasta que se cumpla una
condicin establecida.

a) Lazo while

no MATLAB
Condicin
while <condicin>
si accin
end
Accin 1

Ej:
% epsilon.m
x=1;
while (1+x>1)
x=x/2;
end
eps=2*x

Lazo for

for i=min:p:max
accin
|
|
end

i=variable de conteo
min=limite inferior de conteo
max=limite superior de conteo
p=paso o incremento en el conteo

El for es un ciclo de conteo controlado y se ejecutara mientras la variable de conteo


permanezca dentro del rango especificado.
Si el conteo no a terminado y se desea salir del lazo, ser posible hacerlo usando la
sentencia break.
Crear un programa que ordene ascendentemente los elementos de un vector.

%vecord
v=input('Ingrese un vector')
m=length(v);
for i=1:m-1
for j=(i+1):m
if v(i)>v(j)
temp=v(i);
v(i)=v(j);
v(j)=temp;
end
end
end
disp('Vector ordenado'),v

You might also like