Mudanças entre as edições de "Matlab em uma página"
Linha 35: | Linha 35: | ||
=Pacotes / toolbox= | =Pacotes / toolbox= | ||
− | *Verificando se está instalado | + | *Verificando se está instalado |
− | + | ver | |
− | |||
− | |||
− | |||
*Carregando pacote no octave | *Carregando pacote no octave | ||
pkg load instrument-control | pkg load instrument-control | ||
*Instalando pacote no octave | *Instalando pacote no octave | ||
pkg -forge install instrument-control | pkg -forge install instrument-control | ||
− | |||
=Notas de aula= | =Notas de aula= |
Edição atual tal como às 19h32min de 11 de maio de 2017
Funções de ajuda
- Comando help: mostra ajuda sobre uma função especifica na janela de comando. ex.:
>> help sort %sort é u
- Comando doc: abre a janela de help da função especificada. ex.:
>> doc input
- Comando lookfor: procura pela palavra especificada em toda a documentação do matlab. ex.:
>> lookfor fill
Propriedades de elementos
- Comando whois: obtém informações sobre as variáveis
whois x
- Comando size: obtém tamanho da variável
size x
Limpando a área
clear all; close all; clc;
Trabalhando com imagens
- Material obtido de: Curso Matlab aplicado ao processamento de imagens - Aula 3
- imagem1.jpeg - Imagem de Daniel Teoli Jr, acessível em Link
- imagem2.jpeg - Imagem de Joao Carlos Medau, acessível em Link
- Copiar imagens que se deseja trabalhar para uma certa pasta
- Na barra de navegação do matlab buscar a pasta onde estão as imagens
- Os arquivos deverão aparecer na visão de pastas
- Outra forma de verificar os arquivos é dar o comando "ls" que vai listar os elementos da pasta corrente
- Comando imread: obtém informações pixel a pixel da imagem referida gravando em uma matriz de uint8.
x = imread('imagem1.jpeg')
- Algumas operações interessantes:
size(x) %mostra o tamanho da imagem (pixel em x e pixel em y) max(max(x)) %mostra o maior valor encontrado nas células desta matriz de duas dimensões min(min(x)) %mostra o menor valor encontrado nas células desta matriz de duas dimensões mean(mean(x)) %mostra a média dos valores desta matriz de duas dimensões
Pacotes / toolbox
- Verificando se está instalado
ver
- Carregando pacote no octave
pkg load instrument-control
- Instalando pacote no octave
pkg -forge install instrument-control
Notas de aula
%-- 20-03-2017 19:07:54 --%
%Aula 5, 20/mar
%Endereçamento lógico
v = [1 2 3 4 3 2 1 2]
v([2, 4, 5])
v([false,true,false,true,true,false,false,false])
v >= 3
sum(v>=3)
indices = v >= 3
v(indices)
v(2:5)
u = [1 0 3]
v = [2 5 1 5]
w = [u v]
z = [u, v]
a= [1 2 3; 4 5 6]
b=[10 10 0;10 0 10]
c = [a;b]
z = [u;a]
sort(v)
help sort
sort(v,'descend')
find(u)
v == 5
find(v == 5)
mean(v)
sum(v) / length(v)
mean(a)
mean(mean(a))
lookfor median
u
v
median(v)
ceil(v)
w = [1.2 5 5.8 6.5 9]
ceil(w)
floor(w)
round(w)
t1=[5 5.5 6.5 6 6.25]
t2=[40 43 37 50 45]
t3=[1000 1100 1000 1200 1100]
r1 = t1 .* t2
r2 = sum(r1)
r3 = sum(t3)
r4 = r2 ./ r3
r5 = sum(t2) / sum(t3)
r6 = ((t1 .* t2) ./ t3)
[k, l] = min(r6)
[k, l] = max(r6)
</syntaxhighlight>
%-- 22-03-2017 19:10:04 --%
% aula de 22/mar
var1 = 'Aspas simples definem a variavel como texto'
numero1 = 3
numero1 = 'texto'
var1(1)
var1(1:7)
var1(1:7)'
var1
var3 = [var1, '!']
titulo = 'Numero plot = a: '
numero_plot = 1
titulo_completo = [titulo, numero_plot]
titulo_completo = [titulo, num2str(numero_plot)]
m = ['Plot 1';'Plot 2';'Plot 3']
m(1,:)
m(:,end)
m(:,1)
m(:,end-2)
m(:,end-3:end)
m(:,1:2:end)
clc
%Entrada e saida de dados
Resposta1 = input('Entre com um número: ')
12
Resposta2 = input('Entre seu nome: ');
titulo
Resposta2 = input('Entre seu nome: ');
'Cleber'
doc input
Resposta2 = input('Entre seu nome: ','s');
Cleber
clc
%Mostrando os resultados
Resposta2 = input('Entre seu nome: ','s')
Cleber
Confirm = input(['Voce digitou "',Resposta2,'", confirma?'],'s')
sim
%Comando disp
clc
disp('Frase a ser exibida')
disp(['Voce digitou "',Resposta2,'"'])
numero1 = 48
disp(['Voce digitou ',numero1])
disp(['Voce digitou ',num2str(numero1)])
num1 = [1 2 5 98 2]
num2 = {1 2 5 98 2}
num1(3) = 8
num2{3} = 8
num2{3} = 'texto'
num2{5} = [1 2 3;4 5 6]
num2(5)
num2{5}
titulo = {'Senoide';'Função logaritmica';'Reta'}
size(titulo)
length(titulo)
titulo(1)
titulo{1}
%Concatenação
nova_celula = {titulo{1},titulo{2}}
nova_celula = {titulo(1),titulo(2)}
nova_celula = [titulo(1),titulo(2)]
nova_celula = [titulo(1),titulo{2}]
nova_celula(2)
nova_celula{2}
%Operações
celula_numerica = {12, 42}
celula_numerica'
celula_numerica(1)
celula_numerica{1}
celula_numerica{1} + celula_numerica{1}
celula_numerica{1} = [1 2]
celula_numerica{1} + celula_numerica{1}
celula_numerica{1} + celula_numerica{2}
title(titulo{1})
figure
title(titulo{2})
celula_matriz = {12,'Olá';[1 2 3],[4; 5; 6]}
celula_matriz{2,:}
lookfor right
lookfor fill
str1 = 'nome 1'
zeros(1, 15 - length(str1))
doc cellplot
%Estruturas
banco.nome = 'IFSC'
banco.idade = 108
banco.alunos = 35000
banco
banco.idade
banco(1)
banco(2).nome = 'santander'
banco(2).idade = 200
banco(2).alunos = 20000
doc struct
isfield(banco,'idade')
isfield(banco,'cor')
rmfield(banco,'alunos')
[str1,zeros(1, 15 - length(str1))]
cleber2
cellplot(struct2cell(pontes))
find(pontes(2).localizacao == 'Clark St.')
pontes(2).localizacao == 'Clark St.'
pontes(3).localizacao == 'Clark St.'
find(pontes(3).localizacao == 'Clark St.')
</syntaxhighlight>
peso = input('Entre com seu peso em kg: ');
altura = input('Entre com sua altura em metros: ');
disp(['Seu IMC é: ',num2str(peso./(altura.^2))]);
</syntaxhighlight>
idpontes = 1
pontes(idpontes).localizacao = 'Smith St.';
pontes(idpontes).CargaMax = 80;
pontes(idpontes).Ano = 1928;
pontes(idpontes).AgendaManutencao = 2011;
idpontes = 1 + idpontes
pontes(idpontes).localizacao = 'Hope Ave.';
pontes(idpontes).CargaMax = 90;
pontes(idpontes).Ano = 1950;
pontes(idpontes).AgendaManutencao = 2013;
idpontes = 1 + idpontes
pontes(idpontes).localizacao = 'Clark St.';
pontes(idpontes).CargaMax = 85;
pontes(idpontes).Ano = 1933;
pontes(idpontes).AgendaManutencao = 2012;
idpontes = 1 + idpontes
pontes(idpontes).localizacao = 'North Rd.';
pontes(idpontes).CargaMax = 100;
pontes(idpontes).Ano = 1960;
pontes(idpontes).AgendaManutencao = 2012;
pontes(3).AgendaManutencao = 2018
idpontes = 1 + idpontes
pontes(idpontes).localizacao = 'Shore Rd.';
pontes(idpontes).CargaMax = 85;
pontes(idpontes).Ano = 1997;
pontes(idpontes).AgendaManutencao = 2014;
struct2table(pontes)
</syntaxhighlight>
%Calculadora Switch com Dialog
%Perguntar qual operação deseja utilizar
%Pedir os dois argumentos para realizar a operação
operacao = inputdlg('Digite (+) para soma, (-) para subtração, (*) para multiplicação e (/) para divisão: ')
switch operacao{1}
case '+'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) + str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
case '-'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) - str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
case '*'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) * str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
case '/'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
if str2num(arg2) ~= 0
resultado = str2num(arg1) / str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
else
disp('Não é possível realizar a divisão por zero!')
end
otherwise
disp('Operação inválida!')
end
</syntaxhighlight>
%Calculadora For
%Perguntar qual operação deseja utilizar
%Pedir os dois argumentos para realizar a operação
for i = 1:3
disp(['Execução: ',int2str(i)])
operacao = inputdlg('Digite (+) para soma, (-) para subtração, (*) para multiplicação e (/) para divisão: ');
if strcmp(operacao,'+')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'));
resultado = str2num(arg1) + str2num(arg2);
disp(['Resultado: ',int2str(resultado)])
elseif strcmp(operacao,'-')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'));
resultado = str2num(arg1) - str2num(arg2);
disp(['Resultado: ',int2str(resultado)])
elseif strcmp(operacao,'*')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'));
resultado = str2num(arg1) * str2num(arg2);
disp(['Resultado: ',int2str(resultado)])
elseif strcmp(operacao,'/')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'));
if str2num(arg2) ~= 0
resultado = str2num(arg1) / str2num(arg2);
disp(['Resultado: ',int2str(resultado)])
else
disp('Não é possível realizar a divisão por zero!')
end
else
disp('Operação inválida!')
end
end
</syntaxhighlight>
%Calculadora Switch
%Perguntar qual operação deseja utilizar
%Pedir os dois argumentos para realizar a operação
operacao = input('Digite (+) para soma, (-) para subtração, (*) para multiplicação e (/) para divisão: ','s')
switch operacao
case '+'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) + str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
case '-'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) - str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
case '*'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) * str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
case '/'
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
if str2num(arg2) ~= 0
resultado = str2num(arg1) / str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
else
disp('Não é possível realizar a divisão por zero!')
end
otherwise
disp('Operação inválida!')
end
</syntaxhighlight>
%Calculadora
%Perguntar qual operação deseja utilizar
%Pedir os dois argumentos para realizar a operação
operacao = inputdlg('Digite (+) para soma, (-) para subtração, (*) para multiplicação e (/) para divisão: ')
if strcmp(operacao,'+')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) + str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
elseif strcmp(operacao,'-')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) - str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
elseif strcmp(operacao,'*')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
resultado = str2num(arg1) * str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
elseif strcmp(operacao,'/')
[arg1,arg2] = strtok(input('Digite os dois números separados por espaço: ','s'))
if str2num(arg2) ~= 0
resultado = str2num(arg1) / str2num(arg2)
disp(['Resultado: ',int2str(resultado)])
else
disp('Não é possível realizar a divisão por zero!')
end
else
disp('Operação inválida!')
end
</syntaxhighlight>
%Filtro de segunda ordem
x = 1:1:1000;
y = 1 ./ (1 + x.^2)
loglog(x,y,'bo')
hold off
loglog(x,y,'bo')
x = logspace(0,3,1000)
y = 1 ./ (1 + x.^2)
loglog(x,y,'bo')
x = 1:1:50;
y = 1 ./ (1 + x.^2)
loglog(x,y,'bo')
x = logspace(0,3,50);
y = 1 ./ (1 + x.^2)
y = 1 ./ (1 + x.^2);
loglog(x,y,'bo')
</syntaxhighlight>
%plotlob
x = 1 : 0.1 : 1000;
y = 1 ./ (1 + x.^2)
subplot(2,2,1) %cria um subplot 2x2 e seleciona primeiro quadro
plot (x,y)
grid on
subplot(2,2,2)
semilogx(x,y)
grid on
subplot(2,2,3)
semilogy(x,y)
grid on
subplot(2,2,4)
loglog(x,y)
grid on
</syntaxhighlight>
%polar
convert2deg(pi/6)
t = 0:0.01:6*pi
r = linspace(1,0,1885)
r = linspace(1,0,length(t));
polar(t,r)
plot(t,r)
r = logspace(1,0,length(t))
polar(t,r)
figure
plot(t,r)
</syntaxhighlight>
%Stairs
x=0:10
y=x.^2
plot(x,y)
hold on
stairs(x,y)
grid on
</syntaxhighlight>
%plot
x=0:0.01:4*pi
4*pi
cos(x)
y = cos(x)
plot(x,y)
hold on
z = sin(x);
stem(x,z)
x(1:50:end)
z(1:50:end)
plot(x,y)
hold on
stem(x,z)
hold off
plot(x,y)
hold on
stem(x,z)
hold off
stem(x(1:50:end),z(1:50:end))
stem(y(1:50:end),z(1:50:end))
stem(x(1:50:end),z(1:50:end))
hold on
stem(y(1:50:end),z(1:50:end))
hold off
stem(x(1:50:end),z(1:50:end))
hold on
stem(x(1:50:end),y(1:50:end))
plot(x,z,'b')
plot(x,y,'r')
bar(x(1:50:end),y(1:50:end),'r')
bar(x(1:50:end),z(1:50:end),'b')
</syntaxhighlight>
%plot 3D
t = 0:0.1:10*pi
clc
x = cos(t);
y = sin(t);
z = t;
figure
plot3(x,y,z)
grid on
xlabel('x');ylabel('y');zlabel('z');
view(-90,0)
view(0,0)
%Grade 3D
[X,Y] = meshgrid(-20:0.5:20);
[X,Y] = meshgrid(-20:0.5:20)
R = sqrt(X.^2 + Y.^2) + eps;
clc
Z = sin(R)./R;
mesh(X,Y,Z)
eps
surf(X,Y,Z)
shading flat
clc
shading faceted
shading interp
surfc(X,Y,Z)
contour(X,Y,Z)
meshc(X,Y,Z)
shading interp
meshz(X,Y,Z)
waterfall(X,Y,Z)
</syntaxhighlight>
%plotyy
clc
x = linspace(0 , 4*pi, 1000)
clc
y = 2*sin(x);
z = 30*cos(2*x);
help plotyy
plotyy(x,y,x,z)
doc plotyy
legend('Tensão (V)','Corrente (A)')
doc comet
t = 0:.01:2*pi;
x = cos(2*t).*(cos(t).^2);
y = sin(2*t).*(sin(t).^2);
comet(x,y);
</syntaxhighlight>
%-- 12-04-2017 19:08:37 --%
%Lendo a imagem
x = imread('imagem1.jpeg')
mean(mean(x))
imshow(x)
whos x
y = 255 - x
imshow(y)
title('Negativo da imagem')
%Aumentando o brilho
z = x + 50
%Observar que como é um uint ele está limitado a valores entre 0 e 255 saturando nestes limiares
imshow(x)
imshow(z)
help imshow
imshow(x)
figure
imshow(z)
z = z + 50
imshow(z)
z = z -100;
imshow(z)
imshow(x)
figure
imshow(z)
z = z + 150
imshow(z)
imshow(x)
imshow(z)
figure(1)
figure(2)
z = z - 150;
imshow(z)
size(x)
imwrite(z,'imagem1_modificada1.jpeg')
t = uint8(51 + (204/255)*double(x));
image
figure
imshow(t)
figure
z = x + 51
imshow(z)
limiar = 180;
a = double(x)/limiar;
max(max(a))
b = a.^2;
max(max(b))
c = b * limiar;
max(max(c))
d = uint8(c);
figure
subplot(1,2,1);imshow(x);title('Imagem Original');
subplot(1,2,2);imshow(d);title('Contraste aumentado');
%Aplicando contraste em apenas uma área
e = z
e = x;
e(309:end,243:end) = e(309:end,243:end) + 100;
figure
imshow(e)
%Binarização
f = x >= limiar;
image
imshow(f)
marca = imread('logo.gif')
image
imshow(marca)
help imread
marca0_1 = double(marca)/double(max(max(marca)));
surf(marca0_1)
camada = ones(size(x))
camada(1:size(marca0_1,1),1:size(marca0_1,2)) = marca0_1;
imshow(camada)
g = uint8(double(x) .* camada);
imshow(g)
</syntaxhighlight>
%-- 19-04-2017 19:14:19 --%
guide
help edit
doc guide
inspect
Interface
grid on
handles.axes
Interface
guide
Interface
factorial(52)
sym('factorial(52)')
sym(factorial(52))
sym('2^200 + 1')
sym(2^200 + 1)
e = sym('x^2 + sin(x)')
e = sym('a*x + b')
e = sym('(a*x + b) / (c*y + d)')
pretty(e)
syms x y a b
x
e2 = x^2 + a*x + b
eq1 = sym('x^2 = y')
eq2 = x^2 == y
eq1 = sym('x^2 == y')
eq1 = sym('x^2 = y')
syms x y a b
eq2 = x^2 = y
eq2 = x^2 == y
pretty(eq2)
latex(eq2)
pretty(eq2)
expr = x/a + sin(x) + int(x^2, x, 0, 1)
latex('x/a + sin(x) + int(x^2, x, 0, 1)')
latex(eq2)
latex('x/a + sin(x) + int(x^2, x, 0, 1)')
expr = 'x/a + sin(x) + int(x^2, f(x), 0, 1)'
sym(expr)
latex(sym(expr))
expr = x/a + sin(x) + int(x^2, x, 0, 1)
sym(expr)
latex(sym(expr))
expr
subs(expr, b, 2)
subs(expr, {a, b}, {9, 2})
subs(expr, {a, b, x}, {9, 2, [0 1 2]})
expr
vet = subs(expr, {a, b, x}, {9, 2, [0 1 2]})
sin(1)
vet
double(vet)
expr = x*(x+1)
expand(expr)
expr2 = expand(expr)
expr
expr2
factor(expr2)]
factor(expr2)
prod(factor(expr2))
solve(x^2 - 1 == 0, x)
syms a b c
solve(a*x^2 + b*x + c == 0, x)
pretty(ans)
sol = solve(a*x^2 + b*x + c == 0, x)
sol(1)
a = 10
b = 0.25
c = 0
x = [1:0.1:10]
size(x)
collect(expr3, x)
collect(expr, x)
collect(expr3, y)
collect(expr, y)expr3 = x*y^2 + (1 + x)*y + y^2
expr3 = x*y^2 + (1 + x)*y + y^2
collect(expr3, y)
collect(expr3, x)
implify(expr3)
simplify(expr3)
clc
mupc
mupad
clear all
Interface
hObject
guide
Interface
handles
handles.edtFrequencias.Color = 1
guide
handles.edtFrequencias.ForegroundColor = 1
handles.edtFrequencias.ForegroundColor.Red = 255
handles.edtFrequencias.ForegroundColor = [255,255,255]
handles.edtFrequencias.ForegroundColor = [1,1,1]
Interface
handles.edtFrequencias.ForegroundColor = [1,1,1]
handles.rbtTangente
fdatool
Interface
help if
Interface
help displayDlg
lookfor displaydlg
lookfor dlg
Interface
help printdlg
lookfor dlg
printdlg('teste')
finishdlg('teste')
errordlg('teste')
Interface
help str2int
lookfor str2int
lookfor str2
Interface
guide
Interface
lookfor isstring
lookfor string
Interface
help if
Interface
guide
Interface
function varargout = Interface(varargin)
% INTERFACE MATLAB code for Interface.fig
% INTERFACE, by itself, creates a new INTERFACE or raises the existing
% singleton*.
%
% H = INTERFACE returns the handle to a new INTERFACE or the handle to
% the existing singleton*.
%
% INTERFACE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in INTERFACE.M with the given input arguments.
%
% INTERFACE('Property','Value',...) creates a new INTERFACE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Interface_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Interface_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Interface
% Last Modified by GUIDE v2.5 19-Apr-2017 19:45:52
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Interface_OpeningFcn, ...
'gui_OutputFcn', @Interface_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Interface is made visible.
function Interface_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Interface (see VARARGIN)
handles.contador = 0;
display(handles.contador)
assignin('base','handles',handles)
% Choose default command line output for Interface
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Interface wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = Interface_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in btnDesenhar.
function btnDesenhar_Callback(hObject, eventdata, handles)
% hObject handle to btnDesenhar (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Incrementa o contador
handles.contador = handles.contador + 1;
display(handles.contador)
%handles
%Axis 1
hold(handles.axes1,'off')
amostras = [0:1:1000];
if not(isempty(str2num(get(handles.edtFrequencias,'String'))))
Freq = str2num(get(handles.edtFrequencias,'String'))
onda = 2*pi*Freq*0.001*amostras;
plot(handles.axes1,sin(onda))
grid(handles.axes1,'on')
assignin('base','contador',handles.contador);
assignin('base','hObject',hObject)
% Update handles structure
guidata(hObject, handles);
if (get(handles.rbtCosseno,'Value') == 1)
%Axis 2
plot(handles.axes2,cos(onda))
grid(handles.axes2,'on')
elseif (get(handles.rbtTangente,'Value') == 1)
%Axis 2
plot(handles.axes2,tan(onda))
grid(handles.axes2,'on')
ylim(handles.axes2,[-2,2])
else
errordlg('Selecione uma onda de saída!')
end
end
% --- Executes on button press in rbtCosseno.
function rbtCosseno_Callback(hObject, eventdata, handles)
% hObject handle to rbtCosseno (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of rbtCosseno
set(hObject,'Value',1)
set(handles.rbtTangente,'Value',0)
% --- Executes on button press in rbtTangente.
function rbtTangente_Callback(hObject, eventdata, handles)
% hObject handle to rbtTangente (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of rbtTangente
set(hObject,'Value',1)
set(handles.rbtCosseno,'Value',0)
function edtFrequencias_Callback(hObject, eventdata, handles)
% hObject handle to edtFrequencias (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edtFrequencias as text
% str2double(get(hObject,'String')) returns contents of edtFrequencias as a double
% --- Executes during object creation, after setting all properties.
function edtFrequencias_CreateFcn(hObject, eventdata, handles)
% hObject handle to edtFrequencias (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
</syntaxhighlight>
https://github.com/clebercbr/RobotSimulatorMATLAB.git
function [] = simulation()
bot = createRobot(35,35);
assignin('base','bot',bot);
room = createWorkspace(800,600);
assignin('base','room',room);
roomWithoutBot = room;
configSimulation();
dir = 1;
while 1
room_backup = room;
botNewX = bot.x+dir;
botNewY = bot.y;
retMove = moveRobot(room,bot,botNewX,botNewY);
if retMove == 0
imagesc(room.area)
pbaspect([room.width room.height 1]);
drawnow;
pause(0.02);
else
room = room_backup;
dir = -dir;
end
end
end
function room = createWorkspace(width, height)
%Measures in cm
room.width = width;
room.height = height;
room.area = zeros(room.height,room.width);
%Create desktops
doorW = 100;
doorH = 100;
i = 1;
while i <= 10
desktop(i).object = zeros(60,120)+1;
[y,x] = size(desktop(i).object);
candidateX = randi(room.width-x);
candidateY = randi(room.height-y);
if candidateX > doorW || candidateY > doorH
desktop(i).x = candidateX;
desktop(i).y = candidateY;
room.area(desktop(i).y:desktop(i).y+y-1,desktop(i).x:desktop(i).x+x-1) = desktop(i).object;
i = i + 1;
end
end
assignin('base','desktop',desktop);
%Create chairs
i = 1;
while i <= 20
chair(i).object = zeros(45,45)+1;
[y,x] = size(chair(i).object);
candidateX = randi(room.width-x);
candidateY = randi(room.height-y);
if candidateX > doorW || candidateY > doorH
chair(i).x = candidateX;
chair(i).y = candidateY;
room.area(chair(i).y:chair(i).y+y-1,chair(i).x:chair(i).x+x-1) = chair(i).object;
i = i + 1;
end
end
assignin('base','chair',chair);
end
function robot = createRobot(width, height)
robot.object = zeros(width,height)+1;
robot.width = 35;
robot.height = 35;
%By defalut it initiates in position (1,1) of workspace
robot.x = 1;
robot.y = 1;
end
function ret = moveRobot(room,bot,newX,newY)
sumRoom = sum(sum(room.area));
bot.x = newX;
bot.y = newY;
[y,x] = size(bot.object);
room.area(bot.y:bot.y+y-1,bot.x:bot.x+x-1) = bot.object;
newSumRoom = sum(sum(room.area));
if sumRoom == newSumRoom
ret = 0; %Success
else
room = room_backup;
ret = 1; %Error
end
end
function [] = configSimulation()
figure(1)
colormap(flipud(gray))
grid on
end
</syntaxhighlight>