Matlab - Guardar datos en un vector y graficar

 
Vista:
sin imagen de perfil

Guardar datos en un vector y graficar

Publicado por Gustavo Ivan (6 intervenciones) el 13/06/2015 08:10:38
Hola amigos.
Desearia que me ayuden a resolver un problema que se me presento en Matlab. El problema que tengo es que deseo guardar datos que estoy leyendo atraves del puerto serial, en un vector para despues graficarlos y al mismo tiempo dichos datos guardarlos en un archivo .dat o .txt para despues usarlos.

Segun yo cree un vector para guardar los datos, pero nose si este funcionando correctamente o si esta guardardo los datos. Ando pensando en crear una variable global para almacenar los datos.

Alguien que me pueda ayudar.

De antemano les doy las gracias.
Este es una parte de mi codigo, donde hago la captura de los datos y grafico.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
% --- FUNCIÓN DE RECEPCIÓN SERIAL.
function rx_b_Callback(hObject, eventdata, handles)
% Borrar edit-text de recepción de mensaje
set(handles.editor,'String','')
axes(handles.axes3);
cla reset;
% Desactivar botón actual
set(handles.rx_b,'Enable','off'); pause(0.1)
%global datos
% Matriz de concatenación
handles.acc=[ ];
% Vector para guardar los datos obtenidos de la lectura
datos=zeros( );
tiempo=1;
% Poner a 0 el ID de parada del ciclo "while"
set(handles.stop_b,'UserData',0)
% Ciclo de adquisición
while 1
    if get(handles.stop_b,'UserData') % Verificar ID de parada
        break
    end
    % Si hay datos en buffer de recepción, leerlo
    if handles.Se.BytesAvailable
        lectura=fscanf(handles.Se,'%d'); % Leer buffer de entrada
        tiempo=tiempo+1;
        %A=A(1:end-1); % Quitar "terminator" (~)
        handles.acc=[handles.acc, lectura]; % Concatenar mensaje
        set(handles.editor,'String',handles.acc)% Escribir mensaje
        datos(tiempo)=(lectura(1));
        title('GRAFICA DE TEMPERATURA');
        xlabel('Tiempo (s)');
        ylabel('Temperatura (°C)');
        hold on;
        ylim([0 datos(tiempo)+100]);
        xlim([0 tiempo+10]);
        plot(datos,'LineWidth',2);grid on;
        drawnow
 
 
    end
    pause(0.02);
 
 
end
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de JOSE JEREMIAS CABALLERO
Val: 6.975
Oro
Ha mantenido su posición en Matlab (en relación al último mes)
Gráfica de Matlab

Guardar datos en un vector y graficar

Publicado por JOSE JEREMIAS CABALLERO (5917 intervenciones) el 13/06/2015 13:45:23
Deberias subir todo el código complejo tanto el fig y el m para poder ejecutar tu código y filtrarte de forma mas rápida los errores..





Saludos .
JOSE JEREMÍAS CABALLERO
Asesoría online en Matlab
Servicios de programación matlab
[email protected]
skype: josejeremiascaballero
Estimado Usuario, el correo es para servicios de cursos, asesoría y programación. Toda ayuda gratuita es vía foro.


http://matlabcaballero.blogspot.com
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Guardar datos en un vector y graficar

Publicado por Gustavo Ivan (6 intervenciones) el 18/06/2015 06:13:16
Saludos, este es mi codigo completo, hasta cierto punto ya grafico, pero no de una forma correcta. Ademas al momento de guardar mis datos en un archivo .txt, solo guarda el valor de la temperatura de forma corrida sin salto de linea, aun no consigo guardar la temperatura y tiempo en el mismo instante. Es decir como crear una matriz de 2 x n filas. Dicho valores guardados despues los llamo y los grafico en una ventana aparte.
Espero y me haya explicado


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
function varargout = gui_rx(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @gui_rx_OpeningFcn, ...
                   'gui_OutputFcn',  @gui_rx_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
 
% --- 	CONDICIONES INICIALES DEL PROGRAMA
function gui_rx_OpeningFcn(hObject, eventdata, handles, varargin)
 
% Centrar la GUI
movegui(hObject,'center')
%axes(handles.axes5);
img=imread('inaoe.jpg');
handles.axes5=imshow(img);
img2=imread('itsal.jpg');
handles.axes9=imshow(img2);
% Deshabilitar botón de envío serial y parada del bucle
set(handles.rx_b,'Enable','off')
set(handles.inicio,'Enable','off')
set(handles.stop_b,'Enable','off')
set(handles.parar,'Enable','off')
set(handles.guardar,'Enable','off')
handles.acc=[ ];
global datos
global tiempo valores
valores=0;
tiempo=0;
datos=0;
% Choose default command line output for gui_rx
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
 
% --- Outputs from this function are returned to the command line.
function varargout = gui_rx_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;
 
% --- ABRIR PUERTO SERIAL.
function com_ser_Callback(hObject, eventdata, handles)
% Desactivar botón actual
set(hObject,'Enable','off')
pause(0.1)
% Tomar y verificar el ID del puerto serial
com=get(handles.com_e,'String');
if isempty(com)||isnan(str2double(com))
    return
end
% Obtener  velocidad (baudrate)
contents = get(handles.los_baud,'String');
vel=str2double(contents{get(handles.los_baud,'Value')});
% Configuración del puerto serial
handles.Se = serial(['COM',com]);%Seleccionar puerto COM1
set(handles.Se,'BaudRate',vel);%Velocidad 9600 baudios
set(handles.Se,'DataBits',8);%8 bits de datos
set(handles.Se,'Parity','none');%Sin control de paridad
set(handles.Se,'StopBits',1);%Un bit de parada
set(handles.Se,'FlowControl','none');%Sin control de flujo
set(handles.Se,'Terminator',13);%Terminador
set(handles.Se,'TimeOut',2);%Tiempo de espera
% Abrir el puerto serial
%fopen(handles.Se);
% Mensaje de apertura del puerto serial
msgbox(['Puerto COM',com,' Correcto'],'RS_232')
% Habilitar botón de envío
set(handles.rx_b,'Enable','on')
set(handles.inicio,'Enable','on')
set(handles.stop_b,'Enable','on')
set(handles.parar,'Enable','on')
set(handles.guardar,'Enable','off')
% Actualizar estructura handles
guidata(hObject,handles)
 
% --- FUNCIÓN DE CIERRE DE GUI.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
try
    fclose(handles.Se);%Cerrar puerto serial
catch
end
delete(hObject);
 
% --- FUNCIÓN DE RECEPCIÓN SERIAL.
function rx_b_Callback(hObject, eventdata, handles)
fopen(handles.Se);
% Borrar edit-text de recepción de mensaje
set(handles.editor,'String','')
axes(handles.axes3);
cla reset;
% Desactivar botón actual
set(handles.rx_b,'Enable','off');
set(handles.inicio,'Enable','off');
set(handles.datos_guardados,'Enable','off');
set(handles.abrir_archivo,'Enable','off');
set(handles.abrir,'Enable','off');
pause(0.1)
global datos tiempo valores
% Matriz de concatenación
handles.acc=[ ];
valores=[ ];
% Vector para guardar los datos obtenidos de la lectura
datos=zeros( );
tiempo=1;
% Poner a 0 el ID de parada del ciclo "while"
set(handles.stop_b,'UserData',0)
set(handles.parar,'UserData',0)
% Ciclo de adquisición
while 1
    if get(handles.stop_b,'UserData') % Verificar ID de parada
       get(handles.parar,'UserData')
        break
    end
    % Si hay datos en buffer de recepción, leerlo
    if handles.Se.BytesAvailable
        lectura=fscanf(handles.Se,'%d'); % Leer buffer de entrada
        tiempo=tiempo+1;
        %A=A(1:end-1); % Quitar "terminator" (~)
        valores=[tiempo lectura];
        handles.acc=[handles.acc, lectura]; % Concatenar mensaje
        set(handles.editor,'String',handles.acc)% Escribir mensaje
        datos(tiempo)=(lectura(1));
        title('GRÁFICA DE TEMPERATURA');
        xlabel('Tiempo (s)');
        ylabel('Temperatura (°C)');
        hold on;
        ylim([0 datos(tiempo)+100]);
        xlim([0 tiempo+10]);
        plot(handles.axes3,datos,'LineWidth',2);grid on;box on;
        drawnow
 
    end
    pause(0.02);
 
end
 
 
% ------ FUNCION PARA ADQUIRIR DATOS
function inicio_Callback(hObject, eventdata, handles)
% hObject    handle to inicio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
fopen(handles.Se);
% Borrar edit-text de recepción de mensaje
set(handles.editor,'String','')
axes(handles.axes3);
cla reset;
% Desactivar botón actual
set(handles.rx_b,'Enable','off');
set(handles.inicio,'Enable','off');
set(handles.datos_guardados,'Enable','off');
set(handles.abrir_archivo,'Enable','off');
set(handles.abrir,'Enable','off');
pause(0.1)
global datos tiempo valores
% Matriz de concatenación
handles.acc=[ ];
valores=[ ];
% Vector para guardar los datos obtenidos de la lectura
datos=zeros( );
tiempo=1;
% Poner a 0 el ID de parada del ciclo "while"
set(handles.stop_b,'UserData',0)
set(handles.parar,'UserData',0)
% Ciclo de adquisición
while 1
    if get(handles.stop_b,'UserData') % Verificar ID de parada
       get(handles.parar,'UserData')
        break
    end
    % Si hay datos en buffer de recepción, leerlo
    if handles.Se.BytesAvailable
        lectura=fscanf(handles.Se,'%d'); % Leer buffer de entrada
        tiempo=tiempo+1;
        %A=A(1:end-1); % Quitar "terminator" (~)
        valores=[tiempo lectura];
        handles.acc=[handles.acc, lectura]; % Concatenar mensaje
        set(handles.editor,'String',handles.acc)% Escribir mensaje
        datos(tiempo)=(lectura(1));
        title('GRÁFICA DE TEMPERATURA');
        xlabel('Tiempo (s)');
        ylabel('Temperatura (°C)');
        hold on;
        ylim([0 datos(tiempo)+100]);
        xlim([0 tiempo+10]);
        plot(handles.axes3,datos,'LineWidth',2);grid on;box on;
        drawnow
 
    end
    pause(0.02);
 
end
 
% --- FUNCIÓN DE PARADA DEL CICLO DE ADQUISICIÓN.
function stop_b_Callback(hObject, eventdata, handles)
% Colocar el ID en 1 para romper el ciclo while
set(handles.stop_b,'UserData',1)
set(handles.parar,'UserData',1)
% Cerrar el puerto serial
if strcmp(handles.Se.Status,'open')
    fclose(handles.Se);
    %delete(handles.Se);
end
% Habilitar botones
set(handles.rx_b,'Enable','off')
set(handles.inicio,'Enable','off')
set(handles.com_ser,'Enable','on')
set(handles.guardar,'Enable','on')
set(handles.datos_guardados,'Enable','on')
set(handles.abrir_archivo,'Enable','on')
set(handles.abrir,'Enable','on')
% Borrar edit-text
%set(handles.editor,'String','')
% Mensaje de aviso de cierre del puerto
warndlg('Recepcion Finalizada','WARNING RS-232')
% Actualizar estructura handles
guidata(hObject,handles)
 
 
% ----- FUNCION PARA PARAR EL PUERTO SERIAL
function parar_Callback(hObject, eventdata, handles)
% Colocar el ID en 1 para romper el ciclo while
set(handles.stop_b,'UserData',1)
set(handles.parar,'UserData',1)
% Cerrar el puerto serial
if strcmp(handles.Se.Status,'open')
    fclose(handles.Se);
    %delete(handles.Se);
end
% Habilitar botones
set(handles.rx_b,'Enable','off')
set(handles.inicio,'Enable','off')
set(handles.com_ser,'Enable','on')
set(handles.guardar,'Enable','on')
set(handles.datos_guardados,'Enable','on')
set(handles.abrir_archivo,'Enable','on')
set(handles.abrir,'Enable','on')
% Borrar edit-text
%set(handles.editor,'String','')
% Mensaje de aviso de cierre del puerto
warndlg('Recepcion Finalizada','WARNING RS-232')
% Actualizar estructura handles
guidata(hObject,handles)
 
 
% --- Executes when figure1 is resized.
function figure1_ResizeFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% ----- FUNCION GUARDAR DATOS
function guardar_Callback(hObject, eventdata, handles)
global datos
[filename pathname] = uiputfile( '*.txt');
if filename==0
    return;
else
    datos_nuevos = datos;
    fid=fopen([pathname, filename],'w');
    fprintf(fid,'%d\t\n',datos_nuevos);
    fclose(fid);
    warndlg('Datos guardados correctamente','AVISO')
end
%guidata(hObject,handles);
 
 
% ----- FUNCION PARA BORRAR DATOS
function borrar_Callback(hObject, eventdata, handles)
set(handles.editor,'String','')
axes(handles.axes3);
cla reset;
 
 
% ---- FUNCION PARA ABRIR DATOS
function abrir_Callback(hObject, eventdata, handles)
mostrar_datos;
 
 
% ---- FUNCION PARA CERRAR EL PROGRAMA
function cerrar_Callback(hObject, eventdata, handles)
opc=questdlg('¿Desea salir del programa?','SALIR','Si','No','No');
if strcmp(opc,'No')
    return;
end
 
clear,clc,close all
 
 
% --------------------------------------------------------------------
function archivo_Callback(hObject, eventdata, handles)
% hObject    handle to archivo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% --------------------------------------------------------------------
function editar_Callback(hObject, eventdata, handles)
% hObject    handle to editar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% --------------------------------------------------------------------
function herramientas_Callback(hObject, eventdata, handles)
% hObject    handle to herramientas (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% --------------------------------------------------------------------
function ayuda_Callback(hObject, eventdata, handles)
% hObject    handle to ayuda (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% --------------------------------------------------------------------
function exportar_Callback(hObject, eventdata, handles)
% hObject    handle to exportar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% --------------------------------------------------------------------
function informacion_Callback(hObject, eventdata, handles)
% hObject    handle to informacion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
 
 
% --- Executes on button press in datos_guardados.
function datos_guardados_Callback(hObject, eventdata, handles)
% hObject    handle to datos_guardados (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
mostrar_datos;
 
 
% --------------------------------------------------------------------
function abrir_archivo_ClickedCallback(hObject, eventdata, handles)
mostrar_datos;
 
 
% --------------------------------------------------------------------
function guardar_figura_ClickedCallback(hObject, eventdata, handles)
global datos
[filename pathname] = uiputfile( '*.txt');
if filename==0
    return;
else
    datos_nuevos = datos;
    fid=fopen([pathname, filename],'w');
    fprintf(fid,'%d\t\n',datos_nuevos);
    fclose(fid);
    warndlg('Datos guardados correctamente','AVISO')
end
%guidata(hObject,handles);
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Guardar datos en un vector y graficar

Publicado por Gustavo Ivan (6 intervenciones) el 18/06/2015 06:25:40
prueba

Asi es como luce mi interfaz grafica por el momento, al final le adjunto los archivo que estoy utilizando, tanto el archivo.m y .fig. Si nota en el static text solo aparece el valor de la temperatura, pero no me dice en que tiempo se tomo la lectura y esos mismo valores deseo guardarlos en un archivo .txt

Le agradezco su ayuda, muchas gracias.


Saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar