Instrucciones if/else y while

Slides:



Advertisements
Presentaciones similares
Introducción/repaso a MATLAB
Advertisements

Facultad de Ingeniería UNIVERSIDAD DE MENDOZA
Programación en Matlab
Ejercicios con listas.
1 DEFINITION OF A CIRCLE and example CIRCLES PROBLEM 1a PROBLEM 2a Standard 4, 9, 17 PROBLEM 1b PROBLEM 2b PROBLEM 3 END SHOW PRESENTATION CREATED BY SIMON.
Programación en Matlab
Instrucciones if/else y while
Question words question WORDS? Cómo Cuándo Cuánto Dónde Por qué Qué Cuál Quién A qué hora Adónde.
4.1 Continuidad en un punto 4.2 Tipos de discontinuidades 4.3 Continuidad en intervalos.
Gráficas de funciones Con Matlab.
HYPERBOLAS Standard 4, 9, 16, 17 DEFINITION OF A HYPERBOLA
UNIVERSIDAD DE PUERTO RICO RECINTO UNIVERSITARIO DE MAYAGÜEZ Departamento de Ingeniería Industrial CENTRO DE CÓMPUTO INGENIERÍA INDUSTRIAL 2006.
What has to be done today? It can be done in any order. Make a new ALC form Do the ALC Get two popsicle sticks Get 16 feet of yarn. That is 4 arms width.
Sesión 14: Python (5) – Aplicaciones. 2009/1 Circuitos Digitales III 2010/1 Circuitos Digitales III 2010/1 Circuitos Digitales III 2010/1 Informática.
Do Now Copy the sentences. For 1-4, conjugate the verbs in the preterite tense. 1.Ellos ____________ papas fritas anoche. (comer) 2.Yo _____ al parque.
Programación con MATLAB 5.3
Tutorial de MATLAB para Pronóstico Numérico 1er Cuatrimestre 2008.
Introducción/repaso a MATLAB Procesamiento de Señales 1 Germán Montoya, Universidad Pontificia Bolivariana Medellín,
ALC 7 La fecha es jueves el 7 de septiembre Pasa y recoge un libro para leer.
Estatutos en Scilab 3.1 De entrada y salida estándar.
LAS PREGUNTAS (Question Formation). Asking “yes/no” questions To ask spoken questions that can be answered with a simple “yes” or “no,” simply raise the.
AYUDANTÍA 2 Lenguaje Imperativo y Java. Punteros Dirección a memoria (puede apuntar a NULL). Permite trabajar con memoria (variables dinámicas de heap).
Matlab Matrices. Matriz como tabla de números >> notas=[4.5,5.6; 5.3, 6.2; 3.7,4.9] notas = >> v=size(notas)
Spanish I Week 16. Para Empezar 7 de diciembre Por favor responde a la pregunta en español. Please respond to the question in Spanish ¿Qué llevas hoy?
MATLAB 7 EJERCICIOS. E01. Escribir un programa que permita determinar si un número entero dado es par o impar. (Utilizar el operador mod) E02. Utilizando.
Copyright © 2005 – 2006 MES-English.com. Blue Yellow.
Control, adquisición y monitoreo con Arduino y Visual Basic .net
Introducción a JAVA COMP 250.
Clase 9: Repaso/Resumen
¿Cómo almacenar grandes cantidades de datos?
Olimpiadas Chilenas de Informática - Formación
¿Cómo almacenar grandes cantidades de datos?
Introducción al OCTAVE
Clase 9: Repaso/Resumen
OPERADORES LÓGICOS V F P Q (5<8) && (5<10) es verdadero V V
MATLAB lenguaje interpretado: instrucciones se ejecutan (interpretan) de inmediato ejemplo: >>x = [1 2 3 ; 4 5 6] x = Tipo de dato fundamental:
METODOLOGÍA DE LA PROGRAMACIÓN
Colors Spanish Señora Watts.
“Escritura” formateada a un string
Clase 9: Repaso/Resumen
Ecuación de Segundo Grado
Clase 7: Abreviaturas Valeria Herskovic –
Clase 9: Repaso/Resumen
Hoy es miércoles el veinte de septiembre
Español 1 14 y 17 de octubre de 2016.
Paul Leger Uso de Condicionales Paul Leger
Tema 7. Introducción a lenguaje de programación Visual Basic (clase 2)
MÉTODOS NUMERICOS PARA SOLUCION DE ECUACIONES Parte2
La rama de la matemática que tiene el propósito del desarrollo de métodos, para solucionar los problemas más diversos mediante una cantidad finita de operaciones.
2.1 POTENCIAS Y RADICALES.
El secreto de los signos
Universidad de las Ciencias Informáticas
Método de la bisección Se trata de encontrar los ceros de f(x) = 0
Youden Analysis. Introduction to W. J. Youden Components of the Youden Graph Calculations Getting the “Circle” What to do with the results.
Clase Función cuadrática cuadrática. Función cuadrática Definición Es de la forma: f(x) = ax 2 + bx + c Ejemplos: y su representación gráfica corresponde.
Tema 9. Estructuras de repetición. Clase 2
Tema 9. Estructuras de repetición. Clase 3
The Five Color River! The Cano Cristales river, or the five color river, as the locals call it, starts its journey at the foot of a Colombian mountain.
REFERENCIA DE MATLAB 1/58.
Las figuras geométricas
Pascal Operadores y funciones
Proyecto: Mi horario Nombre Hora Fecha.
Tipos de Ecuaciones. El signo igual El signo igual se utiliza en: El signo igual se utiliza en: Igualdades numéricas: Igualdades numéricas: = 5.
Kindergarten Spanish High Frequency Words
Diego Hernández R Pascal Variables Diego Hernández R
Introducción a la Computación Numérica
Instrucciones if/else y while
Tema 7. Introducción a lenguaje de programación Visual Basic (clase 2)
To insert audio you need to be on that slide
Tema 8. Estructuras de decisión. Clases 1 y 2.
Transcripción de la presentación:

Instrucciones if/else y while if expresión lógica %instrucciones MATLAB elseif expresión2 %opcional %instrucciones … %otros elseif else %opcional end while expresión lógica % instrucciones MATLAB

Operador símbolo prioridad (expresión) ( ) potencia ^ . ^ 1 unarios + - ~ (negación) 2 mult, división * / \ .* ./ .\ 3 Suma, resta + - 4 Operador : : 5 relacional < <= > >= == ~= 6 AND & 7 OR | 8 asignación = 9

Instrucción for >>for i=1:10 %for variable=vector disp(i); %instrucciones end >>a=1:10; >>for i=a disp(a(i)); >>for i=1:length(a) %largo de arreglo

Funciones con varios resultados %f23(x): calcula x al cuadrado y al cubo function[xx,xxx] = f23(x) xx = x.^2; xxx = x.^3; >>[ a b ] = f23(2) a = 4 b = 8 >>f23(2) ans =

Funciones internas (locales) %f23(x): calcula x cuadrado y x cubo function[xx,xxx] = f23(x) xx = x.^2; xxx = cubo(x); function y=cubo(x) %visible en archivo y = x.^3;

Raices de ecuación de 2º grado %raices(a,b,c): raíces de axx+bx+c=0 function[r1,r2] = raices(a,b,c) d=b^2 - 4*a*c; %discriminante if a=0 | d<0 error(‘a=0 o sin raices reales’); %aborta elseif d=0 warning(‘raices iguales’);%muestra mensaje end r1=(-b + sqrt(d))/(2*a); r2=(-b - sqrt(d))/(2*a); >>[x y]=raices(1,4,3) >>[x y]=raices(1,1,4) x=-1 y=-3 a=0 o sin raices reales

Ejercicio: Calcular raíz por el método de búsqueda binaria Algoritmo: determinar x como punto medio del intervalo si f(x) tiene el mismo signo de f(a) entonces repetir el proceso en intervalo [x,b] si f(x) tiene el mismo signo de f(b) entonces repetir el proceso en intervalo [a,x] Nota. Las iteraciones se detienen cuando el tamaño del intervalo de búsqueda alcance un epsilon. x=(a+b)/2 a f(b) f(a) b function r=raiz(a,b,eps)

Solución iterativa %raiz(a,b,eps): raiz de f en [a,b] c/prec eps function r=raiz(a,b,eps) while b-a > eps x=(a+b)/2; if signo(f(x))==signo(f(a)) a=x; else b=x; end end r=(a+b)/2 %signo(x) devuelve -1, 0 o 1 function r=signo(x) if x<0 r=-1; elseif x>0 r=1; else r=0; end

Solución recursiva %raiz(a,b,eps): raiz de f en [a,b] c/prec eps function r=raiz(a,b,eps) x=(a+b)/2; if b-a <= eps r=x; else if signo(f(x)) == signo(f(a)) r=raiz(x,b,eps); r=raiz(a,x,eps); end

“Escritura” formateada a un string a=sprintf(formato,X,…); Escribe el dato X en el string a bajo el control del string formato Ejemplos: >> a=sprintf('x=%g',pi) a = x=3.14159 %Jalisco: nunca pierde n=input('n°? '); disp( sprintf('gano yo con %g',n+1) ); Notas %g se reemplaza por el valor de X %s se usa para strings

Ejemplo con strings >>a=rand(2,3); >>[filas cols]=size(a); >>for i=1:filas linea=sprintf('fila %g: ',i); for j=1:cols linea=sprintf('%s%g ',linea, a(i,j)); end disp(linea); fila 1: 0.921813 0.176266 0.93547 fila 2: 0.738207 0.405706 0.916904

Grabar y leer arreglo %grabar arreglo datos=zeros(2,100); clase 20: MATLAB Grabar y leer arreglo %grabar arreglo datos=zeros(2,100); datos(1,:)=linspace(0,2*pi,100);%angulos datos(2,:)=sin(datos(1,:)); %senos save datos %leer arreglo load datos x=datos(1,:); y=datos(2,:); J.Alvarez

>>x=linspace(-pi,pi,100); plot(x,sin(x))

title(‘…’) xlabel(‘…’) ylabel(‘…’)

plot(x,y,’r’) %color red

plot(x,y,’k:’); %negro y puntos

plot(x,y,’…’) Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is a character string made from one element from any or all the following 3 columns: b blue . point - solid g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star (none) no line y yellow s square k black d diamond v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus at each data point; PLOT(X,Y,'bd') plots blue diamond at each data point but does not draw any line.

>> x=linspace(-pi,pi,20); >> plot(x,sin(x),'r-- >> x=linspace(-pi,pi,20); >> plot(x,sin(x),'r--*',x,cos(x),'b--o') >> legend('seno','coseno')

>> hold on >> plot(x,sin(x),'r-- >> hold on >> plot(x,sin(x),'r--*') >> plot(x,cos(x),'b--o') >> legend('seno','coseno')

axis([-pi,pi,-1,1])

>> subplot(2,1,1), plot(x,sin(x),'r-- >> subplot(2,1,1), plot(x,sin(x),'r--*'), title('seno') >> subplot(2,1,2), plot(x,cos(x),'r--*'), title('coseno')

>> rectangle('Curvature',[1 1])

[x y z]=sphere(30); mesh(x,y,z)

clase 20: MATLAB surf(x,y,z) J.Alvarez