Select the types of activity you want to include in your feed.
[READ-ONLY] Mirror of https://github.com/jmrplens/EASEPostFile2Matlab. Representa los datos de historia temporal obtenidos con EASE 4 y calcula la teoría revisada corregida.
···11+function Centro01 = EASEPost2Distan(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% CENTRO01 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% CENTRO01 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Centro01 = importfile('Centro_01.txt', [16,22], [16,22]);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/02/28 00:31:51
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = [16,22];
2020+ endRow = [16,22];
2121+end
2222+2323+%% Format for each line of text:
2424+% column3: double (%f)
2525+% column4: double (%f)
2626+% column5: double (%f)
2727+% For more information, see the TEXTSCAN documentation.
2828+formatSpec = '%*s%*s%f%f%f%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]';
2929+3030+%% Open the text file.
3131+fileID = fopen(filename,'r');
3232+3333+%% Read columns of data according to the format.
3434+% This call is based on the structure of the file used to generate this
3535+% code. If an error occurs for a different file, try regenerating the code
3636+% from the Import Tool.
3737+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
3838+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
3939+for block=2:length(startRow)
4040+ frewind(fileID);
4141+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
4242+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
4343+ for col=1:length(dataArray)
4444+ dataArray{col} = [dataArray{col};dataArrayBlock{col}];
4545+ end
4646+end
4747+4848+%% Close the text file.
4949+fclose(fileID);
5050+5151+%% Post processing for unimportable data.
5252+% No unimportable data rules were applied during the import, so no post
5353+% processing code is included. To generate code which works for
5454+% unimportable data, select unimportable cells in a file and regenerate the
5555+% script.
5656+5757+%% Create output variable
5858+Centro01 = [dataArray{1:end-1}];
+55
include/EASEPost2Info.m
···11+function Centro01 = EASEPost2Info(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% CENTRO01 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% CENTRO01 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Centro01 = importfile('Centro_01.txt', [15,21], [15,21]);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/02/28 00:51:16
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = [15,21];
2020+ endRow = [15,21];
2121+end
2222+2323+%% Format for each line of text:
2424+% column2: text (%s)
2525+% For more information, see the TEXTSCAN documentation.
2626+formatSpec = '%*s%s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]';
2727+2828+%% Open the text file.
2929+fileID = fopen(filename,'r');
3030+3131+%% Read columns of data according to the format.
3232+% This call is based on the structure of the file used to generate this
3333+% code. If an error occurs for a different file, try regenerating the code
3434+% from the Import Tool.
3535+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
3636+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
3737+for block=2:length(startRow)
3838+ frewind(fileID);
3939+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
4040+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
4141+ dataArray{1} = [dataArray{1};dataArrayBlock{1}];
4242+end
4343+4444+%% Close the text file.
4545+fclose(fileID);
4646+4747+%% Post processing for unimportable data.
4848+% No unimportable data rules were applied during the import, so no post
4949+% processing code is included. To generate code which works for
5050+% unimportable data, select unimportable cells in a file and regenerate the
5151+% script.
5252+5353+%% Create output variable
5454+Centro01 = [dataArray{1:end-1}];
5555+
+77
include/EASEPost2Matrix.m
···11+function Centro1 = EASEPost2Matrix(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% CENTRO1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% CENTRO1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Centro1 = importfile('Centro_1.txt', 31, 61966);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/02/27 22:06:29
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = 31;
2020+ endRow = inf;
2121+end
2222+2323+%% Format for each line of text:
2424+% column2: double (%f)
2525+% column3: double (%f)
2626+% column4: double (%f)
2727+% column5: double (%f)
2828+% column6: double (%f)
2929+% column7: double (%f)
3030+% column8: double (%f)
3131+% column9: double (%f)
3232+% column10: double (%f)
3333+% column11: double (%f)
3434+% column12: double (%f)
3535+% column13: double (%f)
3636+% column14: double (%f)
3737+% column15: double (%f)
3838+% column16: double (%f)
3939+% column17: double (%f)
4040+% column18: double (%f)
4141+% column19: double (%f)
4242+% column20: double (%f)
4343+% column21: double (%f)
4444+% column22: double (%f)
4545+% column23: double (%f)
4646+% For more information, see the TEXTSCAN documentation.
4747+formatSpec = '%*s%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%*s%*s%*s%[^\n\r]';
4848+4949+%% Open the text file.
5050+fileID = fopen(filename,'r');
5151+5252+%% Read columns of data according to the format.
5353+% This call is based on the structure of the file used to generate this
5454+% code. If an error occurs for a different file, try regenerating the code
5555+% from the Import Tool.
5656+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
5757+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'EmptyValue', NaN, 'ReturnOnError', false, 'EndOfLine', '\r\n');
5858+for block=2:length(startRow)
5959+ frewind(fileID);
6060+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
6161+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'EmptyValue', NaN, 'ReturnOnError', false, 'EndOfLine', '\r\n');
6262+ for col=1:length(dataArray)
6363+ dataArray{col} = [dataArray{col};dataArrayBlock{col}];
6464+ end
6565+end
6666+6767+%% Close the text file.
6868+fclose(fileID);
6969+7070+%% Post processing for unimportable data.
7171+% No unimportable data rules were applied during the import, so no post
7272+% processing code is included. To generate code which works for
7373+% unimportable data, select unimportable cells in a file and regenerate the
7474+% script.
7575+7676+%% Create output variable
7777+Centro1 = [dataArray{1:end-1}];
+54
include/EASEPost2Otros.m
···11+function Esquina1 = EASEPost2Otros(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Esquina1 = importfile('Esquina_1.txt', [18,24,29], [18,24,29]);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/03/02 01:50:48
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = [18,24,29];
2020+ endRow = [18,24,29];
2121+end
2222+2323+%% Format for each line of text:
2424+% column4: double (%f)
2525+% For more information, see the TEXTSCAN documentation.
2626+formatSpec = '%*s%*s%*s%f%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]';
2727+2828+%% Open the text file.
2929+fileID = fopen(filename,'r');
3030+3131+%% Read columns of data according to the format.
3232+% This call is based on the structure of the file used to generate this
3333+% code. If an error occurs for a different file, try regenerating the code
3434+% from the Import Tool.
3535+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
3636+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
3737+for block=2:length(startRow)
3838+ frewind(fileID);
3939+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
4040+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
4141+ dataArray{1} = [dataArray{1};dataArrayBlock{1}];
4242+end
4343+4444+%% Close the text file.
4545+fclose(fileID);
4646+4747+%% Post processing for unimportable data.
4848+% No unimportable data rules were applied during the import, so no post
4949+% processing code is included. To generate code which works for
5050+% unimportable data, select unimportable cells in a file and regenerate the
5151+% script.
5252+5353+%% Create output variable
5454+Esquina1 = [dataArray{1:end-1}];
+76
include/EASEPost2Param.m
···11+function Esquina1 = EASEPost2Param(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Esquina1 = importfile('Esquina_1.txt', [11,28], [12,28]);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/03/02 02:08:49
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = [11,28];
2020+ endRow = [12,28];
2121+end
2222+2323+%% Format for each line of text:
2424+% column3: double (%f)
2525+% column4: double (%f)
2626+% column5: double (%f)
2727+% column6: double (%f)
2828+% column7: double (%f)
2929+% column8: double (%f)
3030+% column9: double (%f)
3131+% column10: double (%f)
3232+% column11: double (%f)
3333+% column12: double (%f)
3434+% column13: double (%f)
3535+% column14: double (%f)
3636+% column15: double (%f)
3737+% column16: double (%f)
3838+% column17: double (%f)
3939+% column18: double (%f)
4040+% column19: double (%f)
4141+% column20: double (%f)
4242+% column21: double (%f)
4343+% column22: double (%f)
4444+% column23: double (%f)
4545+% For more information, see the TEXTSCAN documentation.
4646+formatSpec = '%*s%*s%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%*s%*s%*s%[^\n\r]';
4747+4848+%% Open the text file.
4949+fileID = fopen(filename,'r');
5050+5151+%% Read columns of data according to the format.
5252+% This call is based on the structure of the file used to generate this
5353+% code. If an error occurs for a different file, try regenerating the code
5454+% from the Import Tool.
5555+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
5656+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
5757+for block=2:length(startRow)
5858+ frewind(fileID);
5959+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
6060+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
6161+ for col=1:length(dataArray)
6262+ dataArray{col} = [dataArray{col};dataArrayBlock{col}];
6363+ end
6464+end
6565+6666+%% Close the text file.
6767+fclose(fileID);
6868+6969+%% Post processing for unimportable data.
7070+% No unimportable data rules were applied during the import, so no post
7171+% processing code is included. To generate code which works for
7272+% unimportable data, select unimportable cells in a file and regenerate the
7373+% script.
7474+7575+%% Create output variable
7676+Esquina1 = [dataArray{1:end-1}];
+76
include/EASEPost2Param2.m
···11+function Esquina1 = EASEPost2Param2(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Esquina1 = importfile('Esquina_1.txt', [13,27], [13,27]);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/03/02 02:11:55
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = [13,27];
2020+ endRow = [13,27];
2121+end
2222+2323+%% Format for each line of text:
2424+% column4: double (%f)
2525+% column5: double (%f)
2626+% column6: double (%f)
2727+% column7: double (%f)
2828+% column8: double (%f)
2929+% column9: double (%f)
3030+% column10: double (%f)
3131+% column11: double (%f)
3232+% column12: double (%f)
3333+% column13: double (%f)
3434+% column14: double (%f)
3535+% column15: double (%f)
3636+% column16: double (%f)
3737+% column17: double (%f)
3838+% column18: double (%f)
3939+% column19: double (%f)
4040+% column20: double (%f)
4141+% column21: double (%f)
4242+% column22: double (%f)
4343+% column23: double (%f)
4444+% column24: double (%f)
4545+% For more information, see the TEXTSCAN documentation.
4646+formatSpec = '%*s%*s%*s%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%*s%*s%[^\n\r]';
4747+4848+%% Open the text file.
4949+fileID = fopen(filename,'r');
5050+5151+%% Read columns of data according to the format.
5252+% This call is based on the structure of the file used to generate this
5353+% code. If an error occurs for a different file, try regenerating the code
5454+% from the Import Tool.
5555+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
5656+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
5757+for block=2:length(startRow)
5858+ frewind(fileID);
5959+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
6060+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
6161+ for col=1:length(dataArray)
6262+ dataArray{col} = [dataArray{col};dataArrayBlock{col}];
6363+ end
6464+end
6565+6666+%% Close the text file.
6767+fclose(fileID);
6868+6969+%% Post processing for unimportable data.
7070+% No unimportable data rules were applied during the import, so no post
7171+% processing code is included. To generate code which works for
7272+% unimportable data, select unimportable cells in a file and regenerate the
7373+% script.
7474+7575+%% Create output variable
7676+Esquina1 = [dataArray{1:end-1}];
+54
include/EASEPost2Sala.m
···11+function Esquina1 = EASEPost2Sala(filename, startRow, endRow)
22+%IMPORTFILE Import numeric data from a text file as a matrix.
33+% ESQUINA1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
44+% the default selection.
55+%
66+% ESQUINA1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
77+% STARTROW through ENDROW of text file FILENAME.
88+%
99+% Example:
1010+% Esquina1 = importfile('Esquina_1.txt', 4, 7);
1111+%
1212+% See also TEXTSCAN.
1313+1414+% Auto-generated by MATLAB on 2018/03/02 01:05:38
1515+1616+%% Initialize variables.
1717+delimiter = ' ';
1818+if nargin<=2
1919+ startRow = 4;
2020+ endRow = 7;
2121+end
2222+2323+%% Format for each line of text:
2424+% column2: double (%f)
2525+% For more information, see the TEXTSCAN documentation.
2626+formatSpec = '%*s%f%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%[^\n\r]';
2727+2828+%% Open the text file.
2929+fileID = fopen(filename,'r');
3030+3131+%% Read columns of data according to the format.
3232+% This call is based on the structure of the file used to generate this
3333+% code. If an error occurs for a different file, try regenerating the code
3434+% from the Import Tool.
3535+textscan(fileID, '%[^\n\r]', startRow(1)-1, 'WhiteSpace', '', 'ReturnOnError', false);
3636+dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
3737+for block=2:length(startRow)
3838+ frewind(fileID);
3939+ textscan(fileID, '%[^\n\r]', startRow(block)-1, 'WhiteSpace', '', 'ReturnOnError', false);
4040+ dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'TextType', 'string', 'ReturnOnError', false, 'EndOfLine', '\r\n');
4141+ dataArray{1} = [dataArray{1};dataArrayBlock{1}];
4242+end
4343+4444+%% Close the text file.
4545+fclose(fileID);
4646+4747+%% Post processing for unimportable data.
4848+% No unimportable data rules were applied during the import, so no post
4949+% processing code is included. To generate code which works for
5050+% unimportable data, select unimportable cells in a file and regenerate the
5151+% script.
5252+5353+%% Create output variable
5454+Esquina1 = [dataArray{1:end-1}];
+26
include/guardarErrores.m
···11+22+function guardarErrores(Ucoef,Pcoef,Distancia,Dist_P,Dist_U)
33+44+a = confint(Ucoef);
55+b = confint(Pcoef);
66+77+% Resolucion de errores
88+x = linspace(min(Distancia),max(Distancia),8);
99+1010+% Puntos de error del campo util
1111+U = Ucoef.a*x.^(Ucoef.b);
1212+Utop = a(2)*x.^(a(4))-U;
1313+Udow = U-a(1)*x.^(a(3));
1414+TUerrores = table(x',U',Utop',Udow','VariableNames',{'x','y','ymas','ymenos'});
1515+1616+writetable(TUerrores,'UtilErrores.dat','Delimiter','\t')
1717+1818+% Puntos campo perjudicial
1919+% Puntos de error del campo util
2020+P = Pcoef.p1*x+Pcoef.p2;
2121+Ptop = (b(2)*x+(b(4)))-P;
2222+Pdow = P-(b(1)*x+(b(3)));
2323+TPerrores = table(x',P',Ptop',Pdow','VariableNames',{'x','y','ymas','ymenos'});
2424+2525+writetable(TPerrores,'PerjudicialErrores.dat','Delimiter','\t')
2626+end
+208
include/importarPostFiles.m
···11+function importarPostFiles(hObject,handles)
22+% Almacena en la aplicacion (handles.SPLm) la variables
33+% Es una variable tipo cell que en cada fila almacena los datos extraidos
44+% de cada fila. Si hay 20 archivos, el cell 'SPLm' tendr� 20 filas.
55+% En las ultimas lineas se puede observar que contiene cada columna.
66+%
77+% Distancia -> Vector de distancias entre cada receptor y la fuente
88+% PosReceptor -> Vector con la posicion del receptor (X,Y,Z)
99+% PosFuente -> Vector con la posicion de la fuente (X,Y,Z)
1010+% Fuente -> Vector con la ID de fuente recibida cada receptor
1111+% Receptor -> Vector con las ID de cada receptor
1212+% Volumen -> Variable que contiene el valor del volumen de la sala
1313+% Superficie -> Variable que contiene el valor de la superficie
1414+% Temperatura -> Variable que contiene el valor de la temperatura
1515+% Humedad -> Variable que contiene el valor de la humedad
1616+% SPLm -> Cell que almacena la historia temporal de cada receptor
1717+% RayoDirecto -> Tiempo de llegada del primer rayo a cada receptor
1818+% RetFuente -> Retardo de la fuente
1919+% NumRayos -> Numero de rayos recibidos por cada receptor
2020+% Reverberacion -> Tiempo de reverberacion de cada archivo
2121+% Absorcion -> Coeficiente de absorcion de cada archivo
2222+% Directividad -> Directividad de las fuentes
2323+% RuidoFondo -> Ruido de fondo de cada archivo
2424+% SPLFuente -> Nivel SPL de las fuentes
2525+2626+%% Importacion de datos
2727+ListaArchivos = handles.ListaArchivos;
2828+2929+%multiWaitbar(handles,'Importando archivos',N/size(PARAMtxt,1),'color','b');
3030+% Inicializacion de variables
3131+Distancia = zeros(size(ListaArchivos,2),1);
3232+PosReceptor = zeros(size(ListaArchivos,2),3);
3333+PosFuente = zeros(size(ListaArchivos,2),3);
3434+RayoDirecto = zeros(size(ListaArchivos,2),1);
3535+RetFuente = zeros(size(ListaArchivos,2),1);
3636+NumRayos = zeros(size(ListaArchivos,2),1);
3737+Reverberacion = zeros(size(ListaArchivos,2),21);
3838+Absorcion = zeros(size(ListaArchivos,2),21);
3939+Directividad = zeros(size(ListaArchivos,2),21);
4040+RuidoFondo = zeros(size(ListaArchivos,2),21);
4141+SPLFuente = zeros(size(ListaArchivos,2),21);
4242+handles.SPLm = cell(size(ListaArchivos,2),21);
4343+for i=1:size(ListaArchivos,2)
4444+4545+ % Distancia entre receptores y fuente
4646+ A = EASEPost2Distan(ListaArchivos{i});
4747+ Distancia(i) = sqrt(...
4848+ (A(1,1)-A(2,1))^2 + (A(1,2)-A(2,2))^2 + (A(1,3)-A(2,3))^2);
4949+ PosReceptor(i,:) = A(1,:);
5050+ PosFuente(i,:) = A(2,:);
5151+5252+ % Nombre de la fuente y de los receptores
5353+ A = EASEPost2Info(ListaArchivos{i});
5454+ Fuente{i} = char(A(2));
5555+ Receptor{i} = char(A(1));
5656+5757+ % Parametros de la sala
5858+ % ToDo: Almacenar la primera vez y el resto comprobar que son iguales, si
5959+ % no son iguales mostrar error y detener la importaci�n
6060+ A = EASEPost2Sala(ListaArchivos{i});
6161+ Volumen = A(1);
6262+ Superficie = A(2);
6363+ Temperatura = A(3);
6464+ Humedad = A(4);
6565+6666+ % Datos varios
6767+ A = EASEPost2Otros(ListaArchivos{i});
6868+ RayoDirecto(i) = A(1);
6969+ RetFuente(i) = A(2);
7070+ NumRayos(i) = A(3);
7171+7272+ % RT, Absorcion de la sala, Directividad fuente
7373+ A = EASEPost2Param(ListaArchivos{i});
7474+ Reverberacion(i,:) = A(1,:);
7575+ Absorcion(i,:) = A(2,:);
7676+ Directividad(i,:) = A(3,:);
7777+7878+ % Ruido de fondo, SPL fuente
7979+ A = EASEPost2Param2(ListaArchivos{i});
8080+ RuidoFondo(i,:) = A(1,:);
8181+ SPLFuente(i,:) = A(2,:);
8282+8383+ % Obtener historia temporal para cada receptor
8484+ % Obtiene una matriz con la columna de delay y los niveles en tercios de
8585+ % octava
8686+ A = EASEPost2Matrix(ListaArchivos{i});
8787+ % Eliminar el delay de llegada, restando el valor minimo de llegada a todo
8888+ % el vector de tiempos. Asi aseguramos que la integracion por rangos
8989+ % temporales sea correcta.
9090+ Tnew = A(:,1) - RayoDirecto(i);
9191+ % Almacenar en el cell 'SPLm' la informacion del archivo actual 'i'
9292+ handles.SPLm{i,1} = []; % Aqui ira el SPL por milisegundo
9393+ handles.SPLm{i,2} = Fuente{i};
9494+ handles.SPLm{i,3} = Receptor{i};
9595+ handles.SPLm{i,4} = PosFuente(i,:);
9696+ handles.SPLm{i,5} = PosReceptor(i,:);
9797+ handles.SPLm{i,6} = Distancia(i);
9898+ handles.SPLm{i,7} = RetFuente(i);
9999+ handles.SPLm{i,8} = NumRayos(i);
100100+ handles.SPLm{i,9} = RayoDirecto(i);
101101+ handles.SPLm{i,10} = Reverberacion(i,:);
102102+ handles.SPLm{i,11} = Absorcion(i,:);
103103+ handles.SPLm{i,12} = RuidoFondo(i,:);
104104+ handles.SPLm{i,13} = SPLFuente(i,:);
105105+ handles.SPLm{i,14} = Directividad(i,:);
106106+ handles.SPLm{i,15} = Volumen;
107107+ handles.SPLm{i,16} = Superficie;
108108+ handles.SPLm{i,17} = Temperatura;
109109+ handles.SPLm{i,18} = Humedad;
110110+ % Historia temporal completa
111111+ handles.SPLm{i,19} = [Tnew,A(:,2:end)];
112112+ % Historia temporal procesada por milisegundo en bandas de octava
113113+ handles.SPLm{i,20} = [];
114114+ % Historia temporal procesada por milisegundo en tercios de octava
115115+ handles.SPLm{i,21} = [];
116116+117117+end
118118+119119+% En primer lugar agrupa los niveles en bloques de 1 milisegundo, ya que hay
120120+% varios niveles por milisegundo, y promedia los valores de cada bloque
121121+for i=1:numel(handles.SPLm(:,1))
122122+123123+124124+ for j=1:max(ceil(handles.SPLm{i,19}(:,1)))
125125+ Ini = find(handles.SPLm{i,19}(:,1)>=j-1,1); % Inicio del bloque de 'j' milisegundos
126126+ Fin = find(handles.SPLm{i,19}(:,1)>j,1)-1; % Fin del bloque de 'j' milisegundos
127127+ % Si ha llegado al final del vector, fin estara vacio y inicio y fin
128128+ % seran iguales para obtener el valor ultimo del vector
129129+ if isempty(find(handles.SPLm{i,19}(:,1)>j,1)); Fin=Ini; end
130130+ % Si el bloque del milisegundo 'j' existe, ini sera menor o igual a fin,
131131+ % si no existe ini sera mayor a fin y no habra valor en ese milisegundo.
132132+ if Ini<=Fin
133133+ Valores = handles.SPLm{i,19}(Ini:Fin,2:end);
134134+135135+ if max(Valores(:)) > 0
136136+ % Suma el bloque por octavas y vuelve a sumar para obtener un valor
137137+ ValMS(j) = 10*log10(sum(sum(10.^(Valores/10),1)));
138138+ % Suma los rayos recibidos en el milisegundo 'j', y lo pasa de
139139+ % tercios de octava a bandas de octava
140140+ ValMSthirdoct(j,:) = sum(10.^(Valores/10),1);
141141+ ValMSoct(j,:) = 10*log10([sum(ValMSthirdoct(j,1:3)),... % 125 Hz
142142+ sum(ValMSthirdoct(j,4:6)),... % 250 Hz
143143+ sum(ValMSthirdoct(j,7:9)),... % 500 Hz
144144+ sum(ValMSthirdoct(j,10:12)),...% 1 kHz
145145+ sum(ValMSthirdoct(j,13:15)),...% 2 kHz
146146+ sum(ValMSthirdoct(j,16:18)),...% 4 kHz
147147+ sum(ValMSthirdoct(j,19:21))]); % 8 kHz
148148+ ValMSthirdoct(j,:) = 10*log10(ValMSthirdoct(j,:));
149149+ else
150150+ ValMS(j) = 0;
151151+ ValMSoct(j,:) = 0;
152152+ ValMSthirdoct(j,:) = 0;
153153+ end
154154+ else
155155+ ValMS(j)=NaN;
156156+ ValMSoct(j,:) = NaN;
157157+ ValMSthirdoct(j,:) = NaN;
158158+ end
159159+160160+ end
161161+ % Todos los valores 0 y menores a 0 se dejan vacios
162162+ %ValMS(ValMS==0) = NaN;
163163+ %ValMSoct(ValMSoct==0) = NaN;
164164+ % Si se utiliza matlab 2014b o anterior realiza la interpolacion
165165+ % manualmente, sino utiliza la funcion fillmising
166166+ if verLessThan('matlab','8.7')
167167+ % Interpolacion manual global
168168+ bd=isnan(ValMS);
169169+ gd=find(~bd);
170170+ bd([1:(min(gd)-1) (max(gd)+1):end])=0;
171171+ ValMS(bd)=interp1(gd,ValMS(gd),find(bd));
172172+ % Interpolacion manual por bandas
173173+ for jj=1:7
174174+ bd=isnan(ValMSoct(:,jj));
175175+ gd=find(~bd);
176176+ bd([1:(min(gd)-1) (max(gd)+1):end])=0;
177177+ ValMSoct(bd,jj)=interp1(gd,ValMSoct(gd,jj),find(bd));
178178+ end
179179+ for jj=1:21
180180+ bd=isnan(ValMSthirdoct(:,jj));
181181+ gd=find(~bd);
182182+ bd([1:(min(gd)-1) (max(gd)+1):end])=0;
183183+ ValMSthirdoct(bd,jj)=interp1(gd,ValMSthirdoct(gd,jj),find(bd));
184184+ end
185185+ else
186186+ % Interpolar valores en los milisegundos que haya valor 0, desde el inicio
187187+ % al final del vector
188188+ ValMS = fillmissing(ValMS,'linear','EndValues','extrap');
189189+ ValMSoct = fillmissing(ValMSoct,'linear','EndValues','extrap');
190190+ ValMSthirdoct = fillmissing(ValMSthirdoct,'linear','EndValues','extrap');
191191+ end
192192+ handles.SPLm{i,1} = ValMS';
193193+ handles.SPLm{i,20} = ValMSoct;
194194+ handles.SPLm{i,21} = ValMSthirdoct;
195195+end
196196+% Obtener el tiempo maximo valor elegible para representacion. Obtiene el
197197+% maximo de cada receptor y despues busca el minimo entre estos.
198198+handles.MaxElegible = min(cell2mat(cellfun( @(val) numel(val), handles.SPLm(:,1),'UniformOutput',0)))-1;
199199+200200+% Ordenar los datos segun la ID de fuente y despues por receptor. Asi se
201201+% tiene agrupados los datos segun la fuente, necesario para elegir una
202202+% fuente u otra en el programa.
203203+handles.SPLm = sortrows(handles.SPLm,[2,3]);
204204+% Actualizar variable en la aplicacion
205205+guidata(hObject, handles);
206206+207207+end
208208+
+824
include/multiWaitbar.m
···11+function cancel = multiWaitbar( handles,label, varargin )
22+%multiWaitbar: add, remove or update an entry on the multi waitbar
33+%
44+% multiWaitbar(LABEL,VALUE) adds a waitbar for the specified label, or
55+% if it already exists updates the value. LABEL must be a string and
66+% VALUE a number between zero and one or the string 'Close' to remove the
77+% entry Setting value equal to 0 or 'Reset' will cause the progress bar
88+% to reset and the time estimate to be re-initialized.
99+%
1010+% multiWaitbar(LABEL,COMMAND,VALUE,...) or
1111+% multiWaitbar(LABEL,VALUE,COMMAND,VALUE,...)
1212+% passes one or more command/value pairs for changing the named waitbar
1313+% entry. Possible commands include:
1414+% 'Value' Set the value of the named waitbar entry. The
1515+% corresponding value must be a number between 0 and 1.
1616+% 'Increment' Increment the value of the named waitbar entry. The
1717+% corresponding value must be a number between 0 and 1.
1818+% 'Color' Change the color of the named waitbar entry. The
1919+% value must be an RGB triple, e.g. [0.1 0.2 0.3], or a
2020+% single-character color name, e.g. 'r', 'b', 'm'.
2121+% 'Relabel' Change the label of the named waitbar entry. The
2222+% value must be the new name.
2323+% 'Reset' Set the named waitbar entry back to zero and reset its
2424+% timer. No value need be specified.
2525+% 'CanCancel' [on|off] should a "cancel" button be shown for this bar
2626+% (default 'off').
2727+% 'CancelFcn' Function to call in the event that the user cancels.
2828+% 'ResetCancel' Reset the "cancelled" flag for an entry (ie. if you
2929+% decide not to cancel).
3030+% 'Close' Remove the named waitbar entry.
3131+% 'Busy' Puts this waitbar in "busy mode" where a small bar
3232+% bounces back and forth. Return to normal progress display
3333+% using the 'Reset' command.
3434+%
3535+% cancel = multiWaitbar(LABEL,VALUE) also returns whether the user has
3636+% clicked the "cancel" button for this entry (true or false). Two
3737+% mechanisms are provided for cancelling an entry if the 'CanCancel'
3838+% setting is 'on'. The first is just to check the return argument and if
3939+% it is true abort the task. The second is to set a 'CancelFcn' that is
4040+% called when the user clicks the cancel button, much as is done for
4141+% MATLAB's built-in WAITBAR. In either case, you can use the
4242+% 'ResetCancel' command if you don't want to cancel after all.
4343+%
4444+% multiWaitbar('CLOSEALL') closes the waitbar window.
4545+%
4646+% Example:
4747+% multiWaitbar( 'CloseAll' );
4848+% multiWaitbar( 'Task 1', 0 );
4949+% multiWaitbar( 'Task 2', 0.5, 'Color', 'b' );
5050+% multiWaitbar( 'Task 3', 'Busy');
5151+% multiWaitbar( 'Task 1', 'Value', 0.1 );
5252+% multiWaitbar( 'Task 2', 'Increment', 0.2 );
5353+% multiWaitbar( 'Task 3', 'Reset' ); % Disables "busy" mode
5454+% multiWaitbar( 'Task 3', 'Value', 0.3 );
5555+% multiWaitbar( 'Task 2', 'Close' );
5656+% multiWaitbar( 'Task 3', 'Close' );
5757+% multiWaitbar( 'Task 1', 'Close' );
5858+%
5959+% Example:
6060+% multiWaitbar( 'Task 1', 0, 'CancelFcn', @(a,b) disp( ['Cancel ',a] ) );
6161+% for ii=1:100
6262+% abort = multiWaitbar( 'Task 1', ii/100 );
6363+% if abort
6464+% % Here we would normally ask the user if they're sure
6565+% break
6666+% else
6767+% pause( 1 )
6868+% end
6969+% end
7070+% multiWaitbar( 'Task 1', 'Close' )
7171+%
7272+% Example:
7373+% multiWaitbar( 'CloseAll' );
7474+% multiWaitbar( 'Red...', 7/7, 'Color', [0.8 0.0 0.1] );
7575+% multiWaitbar( 'Orange...', 6/7, 'Color', [1.0 0.4 0.0] );
7676+% multiWaitbar( 'Yellow...', 5/7, 'Color', [0.9 0.8 0.2] );
7777+% multiWaitbar( 'Green...', 4/7, 'Color', [0.2 0.9 0.3] );
7878+% multiWaitbar( 'Blue...', 3/7, 'Color', [0.1 0.5 0.8] );
7979+% multiWaitbar( 'Indigo...', 2/7, 'Color', [0.4 0.1 0.5] );
8080+% multiWaitbar( 'Violet...', 1/7, 'Color', [0.8 0.4 0.9] );
8181+%
8282+% Thanks to Jesse Hopkins for suggesting the "busy" mode.
8383+8484+% Author: Ben Tordoff
8585+% Copyright 2007-2014 The MathWorks, Inc.
8686+8787+% Modificaciones para CATT2Matlab
8888+global titleprogress
8989+global timedays
9090+global timehours
9191+global timemins
9292+global timesecs
9393+global timesec
9494+titleprogress = handles.LPROGRESSTITLE;
9595+timedays = handles.LTIMEDAYS;
9696+timehours = handles.LTIMEHOURS;
9797+timemins = handles.LTIMEMINS;
9898+timesecs = handles.LTIMESECS;
9999+timesec = handles.LTIMESEC;
100100+101101+102102+persistent FIGH;
103103+cancel = false;
104104+105105+% Check basic inputs
106106+narginchk( 1, inf); % - kept for backwards compatibility
107107+if ~ischar( label )
108108+ error( 'multiWaitbar:BadArg', 'LABEL must be the name of the progress entry (i.e. a string)' );
109109+end
110110+111111+% Try to get hold of the figure
112112+if isempty( FIGH ) || ~ishandle( FIGH )
113113+ FIGH = findall( 0, 'Type', 'figure', 'Tag', 'multiWaitbar:Figure' );
114114+ if isempty(FIGH)
115115+ FIGH = iCreateFig();
116116+ else
117117+ FIGH = handle( FIGH(1) );
118118+ end
119119+end
120120+121121+% Check for close all and stop early
122122+if any( strcmpi( label, {'CLOSEALL','CLOSE ALL'} ) )
123123+ iDeleteFigure(FIGH);
124124+ return;
125125+end
126126+127127+% Make sure we're on-screen
128128+if ~strcmpi( FIGH.Visible, 'on' )
129129+ FIGH.Visible = 'on';
130130+end
131131+132132+% Get the list of entries and see if this one already exists
133133+entries = getappdata( FIGH, 'ProgressEntries' );
134134+if isempty(entries)
135135+ idx = [];
136136+else
137137+ idx = find( strcmp( label, {entries.Label} ), 1, 'first' );
138138+end
139139+bgcol = getappdata( FIGH, 'DefaultProgressBarBackgroundColor' );
140140+141141+% If it doesn't exist, create it
142142+needs_redraw = false;
143143+entry_added = isempty(idx);
144144+if entry_added
145145+ % Create a new entry
146146+ defbarcolor = getappdata( FIGH, 'DefaultProgressBarColor' );
147147+ entries = iAddEntry( FIGH, entries, label, 0, defbarcolor, bgcol );
148148+ idx = numel( entries );
149149+end
150150+151151+% Check if the user requested a cancel
152152+if nargout
153153+ cancel = entries(idx).Cancel;
154154+end
155155+156156+% Parse the inputs. We shortcut the most common case as an efficiency
157157+force_update = false;
158158+if nargin==2 && isnumeric( varargin{1} )
159159+ entries(idx).LastValue = entries(idx).Value;
160160+ entries(idx).Value = max( 0, min( 1, varargin{1} ) );
161161+ entries(idx).Busy = false;
162162+ needs_update = true;
163163+else
164164+ [params,values] = iParseInputs( varargin{:} );
165165+166166+ needs_update = false;
167167+ for ii=1:numel( params )
168168+ switch upper( params{ii} )
169169+ case 'BUSY'
170170+ entries(idx).Busy = true;
171171+ needs_update = true;
172172+173173+ case 'VALUE'
174174+ entries(idx).LastValue = entries(idx).Value;
175175+ entries(idx).Value = max( 0, min( 1, values{ii} ) );
176176+ entries(idx).Busy = false;
177177+ needs_update = true;
178178+179179+ case {'INC','INCREMENT'}
180180+ entries(idx).LastValue = entries(idx).Value;
181181+ entries(idx).Value = max( 0, min( 1, entries(idx).Value + values{ii} ) );
182182+ entries(idx).Busy = false;
183183+ needs_update = true;
184184+185185+ case {'COLOR','COLOUR'}
186186+ entries(idx).CData = iMakeColors( values{ii}, 16 );
187187+ needs_update = true;
188188+ force_update = true;
189189+190190+ case {'RELABEL', 'UPDATELABEL'}
191191+ % Make sure we have a string as the value and that it
192192+ % doesn't already appear
193193+ if ~ischar( values{ii} )
194194+ error( 'multiWaitbar:BadString', 'Value for ''Relabel'' must be a string.' );
195195+ end
196196+ if ismember( values{ii}, {entries.Label} )
197197+ error( 'multiWaitbar:NameAlreadyExists', 'Cannot relabel an entry to a label that already exists.' );
198198+ end
199199+ entries(idx).Label = values{ii};
200200+ needs_update = true;
201201+ force_update = true;
202202+203203+ case {'CANCANCEL'}
204204+ if ~ischar( values{ii} ) || ~any( strcmpi( values{ii}, {'on','off'} ) )
205205+ error( 'multiWaitbar:BadString', 'Parameter ''CanCancel'' must be a ''on'' or ''off''.' );
206206+ end
207207+ entries(idx).CanCancel = strcmpi( values{ii}, 'on' );
208208+ entries(idx).Cancel = false;
209209+ needs_redraw = true;
210210+211211+ case {'RESETCANCEL'}
212212+ entries(idx).Cancel = false;
213213+ needs_redraw = true;
214214+215215+ case {'CANCELFCN'}
216216+ if ~isa( values{ii}, 'function_handle' )
217217+ error( 'multiWaitbar:BadFunction', 'Parameter ''CancelFcn'' must be a valid function handle.' );
218218+ end
219219+ entries(idx).CancelFcn = values{ii};
220220+ if ~entries(idx).CanCancel
221221+ entries(idx).CanCancel = true;
222222+ end
223223+ needs_redraw = true;
224224+225225+ case {'CLOSE','DONE'}
226226+ if ~isempty(idx)
227227+ % Remove the selected entry
228228+ entries = iDeleteEntry( entries, idx );
229229+ end
230230+ if isempty( entries )
231231+ iDeleteFigure( FIGH );
232232+ % With the window closed, there's nothing else to do
233233+ return;
234234+ else
235235+ needs_redraw = true;
236236+ end
237237+ % We can't continue after clearing the entry, so jump out
238238+ break;
239239+240240+ otherwise
241241+ error( 'multiWaitbar:BadArg', 'Unrecognized command: ''%s''', params{ii} );
242242+243243+ end
244244+ end
245245+end
246246+247247+% Now work out what to update/redraw
248248+if needs_redraw
249249+ setappdata( FIGH, 'ProgressEntries', entries );
250250+ iRedraw( FIGH );
251251+ % NB: Redraw includes updating all bars, so never need to do both
252252+elseif needs_update
253253+ [entries(idx),needs_redraw] = iUpdateEntry( entries(idx), force_update );
254254+ setappdata( FIGH, 'ProgressEntries', entries );
255255+ % NB: if anything was updated onscreen, "needs_redraw" is now true.
256256+end
257257+if entry_added || needs_redraw
258258+ % If the shape or size has changed, do a full redraw, including events
259259+ drawnow();
260260+end
261261+262262+% If we have any "busy" entries, start the timer, otherwise stop it.
263263+myTimer = getappdata( FIGH, 'BusyTimer' );
264264+if any([entries.Busy])
265265+ if strcmpi(myTimer.Running,'off')
266266+ start(myTimer);
267267+ end
268268+else
269269+ if strcmpi(myTimer.Running,'on')
270270+ stop(myTimer);
271271+ end
272272+end
273273+274274+clearvars -global titleprogress timedays timehours timemins timesecs timesec
275275+end % multiWaitbar
276276+277277+278278+%-------------------------------------------------------------------------%
279279+function [params, values] = iParseInputs( varargin )
280280+% Parse the input arguments, extracting a list of commands and values
281281+idx = 1;
282282+params = {};
283283+values = {};
284284+if nargin==0
285285+ return;
286286+end
287287+if isnumeric( varargin{1} )
288288+ params{idx} = 'Value';
289289+ values{idx} = varargin{1};
290290+ idx = idx + 1;
291291+end
292292+293293+while idx <= nargin
294294+ param = varargin{idx};
295295+ if ~ischar( param )
296296+ error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' );
297297+ end
298298+ params{end+1,1} = param; %#ok<AGROW>
299299+ values{end+1,1} = []; %#ok<AGROW>
300300+ switch upper( param )
301301+ case {'DONE','CLOSE','RESETCANCEL'}
302302+ % No value needed, and stop
303303+ break;
304304+ case {'BUSY'}
305305+ % No value needed but parsing should continue
306306+ idx = idx + 1;
307307+ case {'RESET','ZERO','SHOW'}
308308+ % All equivalent to saying ('Value', 0)
309309+ params{end} = 'Value';
310310+ values{end} = 0;
311311+ idx = idx + 1;
312312+ otherwise
313313+ if idx==nargin
314314+ error( 'multiWaitbar:BadSyntax', 'Additional properties must be supplied as property-value pairs' );
315315+ end
316316+ values{end,1} = varargin{idx+1};
317317+ idx = idx + 2;
318318+ end
319319+end
320320+if isempty( params )
321321+ error( 'multiWaitbar:BadSyntax', 'Must specify a value or a command' );
322322+end
323323+end % iParseInputs
324324+325325+%-------------------------------------------------------------------------%
326326+function fobj = iCreateFig()
327327+global titleprogress
328328+% Create the progress bar group window
329329+bgcol = get(0,'DefaultUIControlBackgroundColor');
330330+f = figure( ...
331331+ 'Name', titleprogress, ...
332332+ 'Tag', 'multiWaitbar:Figure', ...
333333+ 'Color', bgcol, ...
334334+ 'MenuBar', 'none', ...
335335+ 'ToolBar', 'none', ...
336336+ 'WindowStyle', 'normal', ... % We don't want to be docked!
337337+ 'HandleVisibility', 'off', ...
338338+ 'IntegerHandle', 'off', ...
339339+ 'Visible', 'off', ...
340340+ 'NumberTitle', 'off' );
341341+% Resize and centre on the first screen
342342+screenSize = get(0,'ScreenSize');
343343+figSz = [360 42];
344344+figPos = ceil((screenSize(1,3:4)-figSz)/2);
345345+fobj = handle( f );
346346+fobj.Position = [figPos, figSz];
347347+setappdata( fobj, 'ProgressEntries', [] );
348348+% Make sure we have the image
349349+defbarcolor = [0.8 0.0 0.1];
350350+barbgcol = uint8( 255*0.75*bgcol );
351351+setappdata( fobj, 'DefaultProgressBarBackgroundColor', barbgcol );
352352+setappdata( fobj, 'DefaultProgressBarColor', defbarcolor );
353353+setappdata( fobj, 'DefaultProgressBarSize', [350 16] );
354354+% Create the timer to use for "Busy" mode, being sure to delete any
355355+% existing ones
356356+delete( timerfind('Tag', 'MultiWaitbarTimer') );
357357+myTimer = timer( ...
358358+ 'TimerFcn', @(src,evt) iTimerFcn(f), ...
359359+ 'Period', 0.02, ...
360360+ 'ExecutionMode', 'FixedRate', ...
361361+ 'Tag', 'MultiWaitbarTimer' );
362362+setappdata( fobj, 'BusyTimer', myTimer );
363363+364364+% Setup the resize function after we've finished setting up the figure to
365365+% avoid excessive redraws
366366+fobj.ResizeFcn = @iRedraw;
367367+fobj.CloseRequestFcn = @iCloseFigure;
368368+end % iCreateFig
369369+370370+%-------------------------------------------------------------------------%
371371+function cdata = iMakeColors( baseColor, height )
372372+% Creates a shiny bar from a single base color
373373+lightColor = [1 1 1];
374374+badColorErrorID = 'multiWaitbar:BadColor';
375375+badColorErrorMsg = 'Colors must be a three element vector [R G B] or a single character (''r'', ''g'' etc.)';
376376+377377+if ischar(baseColor)
378378+ switch upper(baseColor)
379379+ case 'K'
380380+ baseColor = [0.1 0.1 0.1];
381381+ case 'R'
382382+ baseColor = [0.8 0 0];
383383+ case 'G'
384384+ baseColor = [0 0.6 0];
385385+ case 'B'
386386+ baseColor = [0 0 0.8];
387387+ case 'C'
388388+ baseColor = [0.2 0.8 0.9];
389389+ case 'M'
390390+ baseColor = [0.6 0 0.6];
391391+ case 'Y'
392392+ baseColor = [0.9 0.8 0.2];
393393+ case 'W'
394394+ baseColor = [0.9 0.9 0.9];
395395+ otherwise
396396+ error( badColorErrorID, badColorErrorMsg );
397397+ end
398398+else
399399+ if numel(baseColor) ~= 3
400400+ error( badColorErrorID, badColorErrorMsg );
401401+ end
402402+ if isa( baseColor, 'uint8' )
403403+ baseColor = double( baseColor ) / 255;
404404+ elseif isa( baseColor, 'double' )
405405+ if any(baseColor>1) || any(baseColor<0)
406406+ error( 'multiWaitbar:BadColorValue', 'Color values must be in the range 0 to 1 inclusive.' );
407407+ end
408408+ else
409409+ error( badColorErrorID, badColorErrorMsg );
410410+ end
411411+end
412412+413413+% By this point we should have a double precision 3-element vector.
414414+cols = repmat( baseColor, [height, 1] );
415415+416416+breaks = max( 1, round( height * [1 25 50 75 88 100] / 100 ) );
417417+cols(breaks(1),:) = 0.6*baseColor;
418418+cols(breaks(2),:) = lightColor - 0.4*(lightColor-baseColor);
419419+cols(breaks(3),:) = baseColor;
420420+cols(breaks(4),:) = min( baseColor*1.2, 1.0 );
421421+cols(breaks(5),:) = min( baseColor*1.4, 0.95 ) + 0.05;
422422+cols(breaks(6),:) = min( baseColor*1.6, 0.9 ) + 0.1;
423423+424424+y = 1:height;
425425+cols(:,1) = max( 0, min( 1, interp1( breaks, cols(breaks,1), y, 'pchip' ) ) );
426426+cols(:,2) = max( 0, min( 1, interp1( breaks, cols(breaks,2), y, 'pchip' ) ) );
427427+cols(:,3) = max( 0, min( 1, interp1( breaks, cols(breaks,3), y, 'pchip' ) ) );
428428+cdata = uint8( 255 * cat( 3, cols(:,1), cols(:,2), cols(:,3) ) );
429429+end % iMakeColors
430430+431431+432432+%-------------------------------------------------------------------------%
433433+function cdata = iMakeBackground( baseColor, height )
434434+% Creates a shaded background
435435+if isa( baseColor, 'uint8' )
436436+ baseColor = double( baseColor ) / 255;
437437+end
438438+439439+ratio = 1 - exp( -0.5-2*(1:height)/height )';
440440+cdata = uint8( 255 * cat( 3, baseColor(1)*ratio, baseColor(2)*ratio, baseColor(3)*ratio ) );
441441+end % iMakeBackground
442442+443443+%-------------------------------------------------------------------------%
444444+function entries = iAddEntry( parent, entries, label, value, color, bgcolor )
445445+% Add a new entry to the progress bar
446446+447447+% Create bar coloring
448448+psize = getappdata( parent, 'DefaultProgressBarSize' );
449449+cdata = iMakeColors( color, 16 );
450450+% Create background image
451451+barcdata = iMakeBackground( bgcolor, psize(2) );
452452+453453+% Work out the size in advance
454454+labeltext = uicontrol( 'Style', 'Text', ...
455455+ 'String', label, ...
456456+ 'Parent', parent, ...
457457+ 'HorizontalAlignment', 'Left' );
458458+etatext = uicontrol( 'Style', 'Text', ...
459459+ 'String', '', ...
460460+ 'Parent', parent, ...
461461+ 'HorizontalAlignment', 'Right' );
462462+progresswidget = uicontrol( 'Style', 'Checkbox', ...
463463+ 'String', '', ...
464464+ 'Parent', parent, ...
465465+ 'Position', [5 5 psize], ...
466466+ 'CData', barcdata );
467467+cancelwidget = uicontrol( 'Style', 'PushButton', ...
468468+ 'String', '', ...
469469+ 'FontWeight', 'Bold', ...
470470+ 'Parent', parent, ...
471471+ 'Position', [5 5 16 16], ...
472472+ 'CData', iMakeCross( 8 ), ...
473473+ 'Callback', @(src,evt) iCancelEntry( src, label ), ...
474474+ 'Visible', 'off' );
475475+mypanel = uipanel( 'Parent', parent, 'Units', 'Pixels' );
476476+477477+newentry = struct( ...
478478+ 'Label', label, ...
479479+ 'Value', value, ...
480480+ 'LastValue', inf, ...
481481+ 'Created', tic(), ...
482482+ 'LabelText', labeltext, ...
483483+ 'ETAText', etatext, ...
484484+ 'ETAString', '', ...
485485+ 'Progress', progresswidget, ...
486486+ 'ProgressSize', psize, ...
487487+ 'Panel', mypanel, ...
488488+ 'BarCData', barcdata, ...
489489+ 'CData', cdata, ...
490490+ 'BackgroundCData', barcdata, ...
491491+ 'CanCancel', false, ...
492492+ 'CancelFcn', [], ...
493493+ 'CancelButton', cancelwidget, ...
494494+ 'Cancel', false, ...
495495+ 'Busy', false );
496496+if isempty( entries )
497497+ entries = newentry;
498498+else
499499+ entries = [entries;newentry];
500500+end
501501+% Store in figure before the redraw
502502+setappdata( parent, 'ProgressEntries', entries );
503503+if strcmpi( get( parent, 'Visible' ), 'on' )
504504+ iRedraw( parent, [] );
505505+else
506506+ set( parent, 'Visible', 'on' );
507507+end
508508+end % iAddEntry
509509+510510+%-------------------------------------------------------------------------%
511511+function entries = iDeleteEntry( entries, idx )
512512+delete( entries(idx).LabelText );
513513+delete( entries(idx).ETAText );
514514+delete( entries(idx).CancelButton );
515515+delete( entries(idx).Progress );
516516+delete( entries(idx).Panel );
517517+entries(idx,:) = [];
518518+end % iDeleteEntry
519519+520520+%-------------------------------------------------------------------------%
521521+function entries = iCancelEntry( src, name )
522522+figh = ancestor( src, 'figure' );
523523+entries = getappdata( figh, 'ProgressEntries' );
524524+if isempty(entries)
525525+ % The entries have been lost - nothing can be done.
526526+ return
527527+end
528528+idx = find( strcmp( name, {entries.Label} ), 1, 'first' );
529529+530530+% Set the cancel flag so that the user is told on next update
531531+entries(idx).Cancel = true;
532532+setappdata( figh, 'ProgressEntries', entries );
533533+534534+% If a user function is supplied, call it
535535+if ~isempty( entries(idx).CancelFcn )
536536+ feval( entries(idx).CancelFcn, name, 'Cancelled' );
537537+end
538538+539539+end % iCancelEntry
540540+541541+542542+%-------------------------------------------------------------------------%
543543+function [entry,updated] = iUpdateEntry( entry, force )
544544+% Update one progress bar
545545+546546+% Deal with busy entries separately
547547+if entry.Busy
548548+ entry = iUpdateBusyEntry(entry);
549549+ updated = true;
550550+ return;
551551+end
552552+553553+% Some constants
554554+marker_weight = 0.8;
555555+556556+% Check if the label needs updating
557557+updated = force;
558558+val = entry.Value;
559559+lastval = entry.LastValue;
560560+561561+% Now update the bar
562562+psize = entry.ProgressSize;
563563+filled = max( 1, round( val*psize(1) ) );
564564+lastfilled = max( 1, round( lastval*psize(1) ) );
565565+566566+% We do some careful checking so that we only redraw what we have to. This
567567+% makes a small speed difference, but every little helps!
568568+if force || (filled<lastfilled)
569569+ % Create the bar background
570570+ startIdx = 1;
571571+ bgim = entry.BackgroundCData(:,ones( 1, psize(1)-filled ),:);
572572+ barim = iMakeBarImage(entry.CData, startIdx, filled);
573573+ progresscdata = [barim,bgim];
574574+575575+ % Add light/shadow around the markers
576576+ markers = round( (0.1:0.1:val)*psize(1) );
577577+ markers(markers<startIdx | markers>(filled-2)) = [];
578578+ highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)];
579579+ for ii=1:numel( markers )
580580+ progresscdata(:,markers(ii)+[-1,0],:) = highlight;
581581+ end
582582+583583+ % Set the image into the checkbox
584584+ entry.BarCData = progresscdata;
585585+ set( entry.Progress, 'cdata', progresscdata );
586586+ updated = true;
587587+588588+elseif filled > lastfilled
589589+ % Just need to update the existing data
590590+ progresscdata = entry.BarCData;
591591+ startIdx = max(1,lastfilled-1);
592592+ % Repmat is the obvious way to fill the bar, but BSXFUN is often
593593+ % faster. Indexing is obscure but faster still.
594594+ progresscdata(:,startIdx:filled,:) = iMakeBarImage(entry.CData, startIdx, filled);
595595+596596+ % Add light/shadow around the markers
597597+ markers = round( (0.1:0.1:val)*psize(1) );
598598+ markers(markers<startIdx | markers>(filled-2)) = [];
599599+ highlight = [marker_weight*entry.CData, 255 - marker_weight*(255-entry.CData)];
600600+ for ii=1:numel( markers )
601601+ progresscdata(:,markers(ii)+[-1,0],:) = highlight;
602602+ end
603603+604604+ entry.BarCData = progresscdata;
605605+ set( entry.Progress, 'CData', progresscdata );
606606+ updated = true;
607607+end
608608+609609+% As an optimization, don't update any text if the bar didn't move and the
610610+% percentage hasn't changed
611611+decval = round( val*100 );
612612+lastdecval = round( lastval*100 );
613613+614614+if ~updated && (decval == lastdecval)
615615+ return
616616+end
617617+618618+% Now work out the remaining time
619619+minTime = 3; % secs
620620+if val <= 0
621621+ % Zero value, so clear the eta
622622+ entry.Created = tic();
623623+ elapsedtime = 0;
624624+ etaString = '';
625625+else
626626+ elapsedtime = round(toc( entry.Created )); % in seconds
627627+628628+ % Only show the remaining time if we've had time to estimate
629629+ if elapsedtime < minTime
630630+ % Not enough time has passed since starting, so leave blank
631631+ etaString = '';
632632+ else
633633+ % Calculate a rough ETA
634634+ eta = elapsedtime * (1-val) / val;
635635+ etaString = iGetTimeString( eta );
636636+ end
637637+end
638638+639639+if ~isequal( etaString, entry.ETAString )
640640+ set( entry.ETAText, 'String', etaString );
641641+ entry.ETAString = etaString;
642642+ updated = true;
643643+end
644644+645645+% Update the label too
646646+if force || elapsedtime > minTime
647647+ if force || (decval ~= lastdecval)
648648+ labelstr = [entry.Label, sprintf( ' (%d%%)', decval )];
649649+ set( entry.LabelText, 'String', labelstr );
650650+ updated = true;
651651+ end
652652+end
653653+654654+end % iUpdateEntry
655655+656656+function eta = iGetTimeString( remainingtime )
657657+global timedays
658658+global timehours
659659+global timemins
660660+global timesecs
661661+global timesec
662662+if remainingtime > 172800 % 2 days
663663+ eta = [sprintf( '%d ', round(remainingtime/86400) ),timedays];
664664+else
665665+ if remainingtime > 7200 % 2 hours
666666+ eta = [sprintf( '%d ', round(remainingtime/3600) ),timehours];
667667+ else
668668+ if remainingtime > 120 % 2 mins
669669+ eta = [sprintf( '%d ', round(remainingtime/60) ),timemins];
670670+ else
671671+ % Seconds
672672+ remainingtime = round( remainingtime );
673673+ if remainingtime > 1
674674+ eta = [sprintf( '%d ', remainingtime ),timesecs];
675675+ elseif remainingtime == 1
676676+ eta = ['1 ',timesec];
677677+ else
678678+ eta = ''; % Nearly done (<1sec)
679679+ end
680680+ end
681681+ end
682682+end
683683+end % iGetTimeString
684684+685685+686686+%-------------------------------------------------------------------------%
687687+function entry = iUpdateBusyEntry( entry )
688688+% Update a "busy" progress bar
689689+% Make sure the widget is still OK
690690+if ~ishandle(entry.Progress)
691691+ return
692692+end
693693+% Work out the new position. Since the bar is 0.1 long and needs to bounce,
694694+% the position varies from 0 up to 0.9 then back down again. We achieve
695695+% this with judicious use of "mod" with 1.8.
696696+entry.Value = mod(entry.Value+0.01,1.8);
697697+val = entry.Value;
698698+if val>0.9
699699+ % Moving backwards
700700+ val = 1.8-val;
701701+end
702702+psize = entry.ProgressSize;
703703+startIdx = max( 1, round( val*psize(1) ) );
704704+endIdx = max( 1, round( (val+0.1)*psize(1) ) );
705705+barLength = endIdx - startIdx + 1;
706706+707707+% Create the image
708708+bgim = entry.BackgroundCData(:,ones( 1, psize(1) ),:);
709709+barim = iMakeBarImage(entry.CData, 1, barLength);
710710+bgim(:,startIdx:endIdx,:) = barim;
711711+712712+% Put it into the widget
713713+entry.BarCData = bgim;
714714+set( entry.Progress, 'CData', bgim );
715715+end % iUpdateBusyEntry
716716+717717+718718+%-------------------------------------------------------------------------%
719719+function barim = iMakeBarImage(strip, startIdx, endIdx)
720720+shadow1_weight = 0.4;
721721+shadow2_weight = 0.7;
722722+barLength = endIdx - startIdx + 1;
723723+% Repmat is the obvious way to fill the bar, but BSXFUN is often
724724+% faster. Indexing is obscure but faster still.
725725+barim = strip(:,ones(1, barLength),:);
726726+% Add highlight to the start of the bar
727727+if startIdx <= 2 && barLength>=2
728728+ barim(:,1,:) = 255 - shadow1_weight*(255-strip);
729729+ barim(:,2,:) = 255 - shadow2_weight*(255-strip);
730730+end
731731+% Add shadow to the end of the bar
732732+if endIdx>=4 && barLength>=2
733733+ barim(:,end,:) = shadow1_weight*strip;
734734+ barim(:,end-1,:) = shadow2_weight*strip;
735735+end
736736+end % iMakeBarImage
737737+738738+%-------------------------------------------------------------------------%
739739+function iCloseFigure( fig, evt ) %#ok<INUSD>
740740+% Closing the figure just makes it invisible
741741+set( fig, 'Visible', 'off' );
742742+end % iCloseFigure
743743+744744+%-------------------------------------------------------------------------%
745745+function iDeleteFigure( fig )
746746+% Actually destroy the figure
747747+busyTimer = getappdata( fig, 'BusyTimer' );
748748+stop( busyTimer );
749749+delete( busyTimer );
750750+delete( fig );
751751+end % iDeleteFigure
752752+753753+%-------------------------------------------------------------------------%
754754+function iRedraw( fig, evt ) %#ok<INUSD>
755755+entries = getappdata( fig, 'ProgressEntries' );
756756+fobj = handle( fig );
757757+p = fobj.Position;
758758+% p = get( fig, 'Position' );
759759+border = 5;
760760+textheight = 16;
761761+barheight = 16;
762762+panelheight = 10;
763763+N = max( 1, numel( entries ) );
764764+765765+% Check the height is correct
766766+heightperentry = textheight+barheight+panelheight;
767767+requiredheight = 2*border + N*heightperentry - panelheight;
768768+if ~isequal( p(4), requiredheight )
769769+ p(2) = p(2) + p(4) - requiredheight;
770770+ p(4) = requiredheight;
771771+ % In theory setting the position should re-trigger this callback, but
772772+ % in practice it doesn't, probably because we aren't calling "drawnow".
773773+ set( fig, 'Position', p )
774774+end
775775+ypos = p(4) - border;
776776+width = p(3) - 2*border;
777777+setappdata( fig, 'DefaultProgressBarSize', [width barheight] );
778778+779779+for ii=1:numel( entries )
780780+ set( entries(ii).LabelText, 'Position', [border ypos-textheight width*0.75 textheight] );
781781+ set( entries(ii).ETAText, 'Position', [border+width*0.75 ypos-textheight width*0.25 textheight] );
782782+ ypos = ypos - textheight;
783783+ if entries(ii).CanCancel
784784+ set( entries(ii).Progress, 'Position', [border ypos-barheight width-barheight+1 barheight] );
785785+ entries(ii).ProgressSize = [width-barheight barheight];
786786+ set( entries(ii).CancelButton, 'Visible', 'on', 'Position', [p(3)-border-barheight ypos-barheight barheight barheight] );
787787+ else
788788+ set( entries(ii).Progress, 'Position', [border ypos-barheight width+1 barheight] );
789789+ entries(ii).ProgressSize = [width barheight];
790790+ set( entries(ii).CancelButton, 'Visible', 'off' );
791791+ end
792792+ ypos = ypos - barheight;
793793+ set( entries(ii).Panel, 'Position', [-500 ypos-500-panelheight/2 p(3)+1000 500] );
794794+ ypos = ypos - panelheight;
795795+ entries(ii) = iUpdateEntry( entries(ii), true );
796796+end
797797+setappdata( fig, 'ProgressEntries', entries );
798798+end % iRedraw
799799+800800+function cdata = iMakeCross( sz )
801801+% Create a cross-shape icon of size sz*sz*3
802802+803803+cdata = diag(ones(sz,1),0) + diag(ones(sz-1,1),1) + diag(ones(sz-1,1),-1);
804804+cdata = cdata + flip(cdata,2);
805805+806806+% Convert zeros to nans (transparent) and non-zeros to zero (black)
807807+cdata(cdata == 0) = nan;
808808+cdata(~isnan(cdata)) = 0;
809809+810810+% Convert to RGB
811811+cdata = cat( 3, cdata, cdata, cdata );
812812+end % iMakeCross
813813+814814+815815+function iTimerFcn(fig)
816816+% Timer callback for updating stuff every so often
817817+entries = getappdata( fig, 'ProgressEntries' );
818818+for ii=1:numel(entries)
819819+ if entries(ii).Busy
820820+ entries(ii) = iUpdateBusyEntry(entries(ii));
821821+ end
822822+end
823823+setappdata( fig, 'ProgressEntries', entries );
824824+end % iTimerFcn
+21
include/representaAbsorcion.m
···11+function representaAbsorcion(handles)
22+33+axes(handles.plotfig)
44+Absor = handles.SPLm{handles.Index,11};
55+Frecuencia = [125,250,500,1000,2000,4000,8000];
66+Fuente = string(handles.SPLm(handles.Index,2));
77+% Pasar de tercios de octava a octavas
88+Octavas = zeros(1,7);
99+a = 0;
1010+for i=2:3:21
1111+ a = a+1;
1212+ Octavas(a) = (Absor(i-1)+Absor(i)+Absor(i+1))/3;
1313+end
1414+1515+bar(Octavas*100)
1616+set(gca,'XTickLabel', Frecuencia);
1717+1818+title('Coeficientes de absorci�n medio')
1919+xlabel('Frecuencia (Hz)')
2020+ylabel('\alpha (%)')
2121+end
+21
include/representaDirectividad.m
···11+function representaDirectividad(handles)
22+33+axes(handles.plotfig)
44+Resp = handles.SPLm{handles.Index,14};
55+Frecuencia = [125,250,500,1000,2000,4000,8000];
66+Fuente = string(handles.SPLm(handles.Index,2));
77+% Obtener solo el valor de las octavas
88+Octavas = zeros(1,7);
99+a = 0;
1010+for i=2:3:21
1111+ a = a+1;
1212+ Octavas(a) = Resp(i);
1313+end
1414+1515+bar(Octavas)
1616+set(gca,'XTickLabel', Frecuencia);
1717+1818+title(sprintf('Respuesta en frecuencia de la fuente %s',Fuente))
1919+xlabel('Frecuencia (Hz)')
2020+ylabel('DI (dB)')
2121+end
+21
include/representaRT.m
···11+function representaRT(handles)
22+33+axes(handles.plotfig)
44+RT = handles.SPLm{handles.Index,10};
55+Frecuencia = [125,250,500,1000,2000,4000,8000];
66+Fuente = string(handles.SPLm(handles.Index,2));
77+% Pasar de tercios de octava a octavas
88+Octavas = zeros(1,7);
99+a = 0;
1010+for i=2:3:21
1111+ a = a+1;
1212+ Octavas(a) = (RT(i-1)+RT(i)+RT(i+1))/3;
1313+end
1414+1515+bar(Octavas)
1616+set(gca,'XTickLabel', Frecuencia);
1717+1818+title(sprintf('Tiempo de reverberaci�n con la fuente %s',Fuente))
1919+xlabel('Frecuencia (Hz)')
2020+ylabel('Tiempo de reverberaci�n (s)')
2121+end
+21
include/representaRespuesta.m
···11+function representaRespuesta(handles)
22+33+axes(handles.plotfig)
44+Resp = handles.SPLm{handles.Index,13};
55+Frecuencia = [125,250,500,1000,2000,4000,8000];
66+Fuente = string(handles.SPLm(handles.Index,2));
77+% Pasar de tercios de octava a octavas
88+Octavas = zeros(1,7);
99+a = 0;
1010+for i=2:3:21
1111+ a = a+1;
1212+ Octavas(a) = 10*log10(sum(10.^(Resp(i-1)/10)+10.^(Resp(i)/10)+10.^(Resp(i+1)/10)));
1313+end
1414+1515+bar(Octavas)
1616+set(gca,'XTickLabel', Frecuencia);
1717+1818+title(sprintf('Respuesta en frecuencia de la fuente %s',Fuente))
1919+xlabel('Frecuencia (Hz)')
2020+ylabel('Nivel SPL (dB)')
2121+end
+331
include/representarCt.m
···11+function representarCt(hObject,handles)
22+% Reprsentacion del parametro claridad
33+axes(handles.plotfig)
44+55+Rango = handles.Rango;
66+SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar
77+SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas
88+Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor
99+Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas
1010+Fuente = string(handles.SPLm(:,2)');
1111+Receptor = string(handles.SPLm(:,3)');
1212+1313+1414+% Comprobar que bandas de frecuencias se han elegido
1515+Bandas = [];
1616+fsel = [];
1717+if handles.frec125.Value==1
1818+ Bandas = [Bandas,1];
1919+ fsel = [fsel,125];
2020+end
2121+if handles.frec250.Value==1
2222+ Bandas = [Bandas,2];
2323+ fsel = [fsel,250];
2424+end
2525+if handles.frec500.Value==1
2626+ Bandas = [Bandas,3];
2727+ fsel = [fsel,500];
2828+end
2929+if handles.frec1000.Value==1
3030+ Bandas = [Bandas,4];
3131+ fsel = [fsel,1000];
3232+end
3333+if handles.frec2000.Value==1
3434+ Bandas = [Bandas,5];
3535+ fsel = [fsel,2000];
3636+end
3737+if handles.frec4000.Value==1
3838+ Bandas = [Bandas,6];
3939+ fsel = [fsel,4000];
4040+end
4141+if handles.frec8000.Value==1
4242+ Bandas = [Bandas,7];
4343+ fsel = [fsel,8000];
4444+end
4545+if isempty(Bandas); Bandas = 1:7; end
4646+if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end
4747+4848+%% Procesado de datos
4949+% Separacion e integracion de los niveles antes y despues del rango
5050+Dneto = zeros(1,numel(SPLm));
5151+Eneto = zeros(1,numel(SPLm));
5252+Lneto = zeros(1,numel(SPLm));
5353+for i=1:numel(SPLm)
5454+ % Direct - Early - Late EXTRACTION
5555+ Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms
5656+ Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion
5757+ Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito
5858+5959+ % Ponderacion A
6060+ % f = fsel; % Frecuencias seleccionadas
6161+ % ponderacionA = 20*log10(...
6262+ % 12194^2*f.^4 ./...
6363+ % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2;
6464+ % Dbruto = Dbruto + ponderacionA;
6565+ % Ebruto = Ebruto + ponderacionA;
6666+ % Lbruto = Lbruto + ponderacionA;
6767+6868+ % Suma de niveles para los dos rangos
6969+ Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10)));
7070+ Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10)));
7171+ Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10)));
7272+end
7373+7474+% Campo util es la suma del campo directo y el early
7575+Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10));
7676+7777+%% Representacion grafica del campo Util y el Perjudicial
7878+7979+%% Puntos y curva de 0ms a Valor
8080+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
8181+% asociado
8282+Dist_U = sortrows([Distancia',Uneto']);
8383+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
8484+% distancias iguales y elimina el duplicado
8585+[C,~,idx] = unique(Dist_U(:,1),'stable');
8686+val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
8787+Dist_U = [C,val];
8888+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
8989+% receptor mas cercano
9090+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
9191+%Dist_U = [[0;V0_0toVal]';Dist_U];
9292+% Separar los valores para graficar y convertirlo en vector fila
9393+Dist = Dist_U(:,1);
9494+Urec = Dist_U(:,2);
9595+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
9696+% (Ures)
9797+[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1');
9898+Uplot=Ucoef.a*Distplot.^Ucoef.b;
9999+100100+101101+102102+%% Puntos y curva de valor a infinito ms
103103+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
104104+% asociado
105105+Dist_P = sortrows([Distancia',Lneto']);
106106+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
107107+% distancias iguales y elimina el duplicado
108108+[C,~,idx] = unique(Dist_P(:,1),'stable');
109109+val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
110110+Dist_P = [C,val];
111111+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
112112+% receptor mas cercano
113113+%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap');
114114+%Dist_P = [[0;V0_0toVal]';Dist_P];
115115+% Separar los valores para graficar y convertirlo en vector fila
116116+Dist = Dist_P(:,1);
117117+Prec = Dist_P(:,2);
118118+% Obtener coeificentes curva polinomica de grado 1
119119+[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1');
120120+% Crea la curva
121121+Pplot = Pcoef.p1*Distplot+Pcoef.p2;
122122+123123+124124+% Claridad EASE
125125+% Muestra los puntos
126126+plot(Dist,Urec-Prec,'^b','MarkerFaceColor','b'),hold on
127127+% Muestra la curva
128128+Curv(1)=plot(Distplot,Uplot-Pplot,'b','LineWidth',1.2);
129129+130130+% A�ade las rejillas de las graficas
131131+grid on
132132+grid minor
133133+134134+% Leyenda
135135+leyenda{1} = sprintf('C_{%s} - EASE',num2str(Rango));
136136+137137+%% Teoria corregida
138138+% Si se ha marcado el calculo de la teoria revisada corregida se calcula y
139139+% se a�ade a la grafica
140140+if get(handles.teoriacorregida,'value')==1
141141+ %%% PARAMETROS
142142+ % Nivel de presion total de la fuente a 1 metro
143143+ SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10)));
144144+ % Volumen (m3)
145145+ V = handles.SPLm{handles.Index,15};
146146+ % Superficie (m2)
147147+ S = handles.SPLm{handles.Index,16};
148148+ % Mean Free Path
149149+ mfp = 4*V/S;
150150+ % Absorcion media
151151+ alpha = mean(handles.SPLm{handles.Index,11});
152152+ % Absorci�n equivalente de Eyring
153153+ A = -S*log(1-alpha);
154154+ % Temperatura de la sala
155155+ temp = handles.SPLm{handles.Index,17};
156156+ % Velocidad del sonido
157157+ c = 331.4 + 0.6*temp;
158158+ % Densidad del aire. Presion Atm / (constante gas*Temp
159159+ % absoluta)
160160+ rho = 101325 / (287.058*(273.15+temp));
161161+ % Impedancia acustica del aire
162162+ Z = rho*c;
163163+ % Presion de referencia
164164+ pref = 2*10^(-5);
165165+ % Factor de conversion
166166+ Fac = Z/(pref^2);
167167+ % Directividad de la fuente
168168+ Q = str2double(get(handles.Qdir,'string'));
169169+ % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1
170170+ SWL = SPL - 10*log10(1/(4*pi*1));
171171+ % Potencia de la fuente en vatios
172172+ W = 10.^(SWL/10)*10^-12;
173173+ % Tiempo de reverberacion de Eyring
174174+ T = 6*log(10)/c * mfp * 1/(-log(1-alpha));
175175+ % Rango de integracion temporal (s)
176176+ t = handles.Rango * 10^(-3);
177177+178178+ %% Obtencion de la curvas directo y early
179179+ %% Curva del campo directo
180180+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
181181+ % asociado
182182+ Dist_D = sortrows([Distancia',Dneto']);
183183+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
184184+ % distancias iguales y elimina el duplicado
185185+ [C,~,idx] = unique(Dist_D(:,1),'stable');
186186+ val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
187187+ Dist_D = [C,val];
188188+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
189189+ % receptor mas cercano
190190+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
191191+ %Dist_U = [[0;V0_0toVal]';Dist_U];
192192+ % Separar los valores para graficar y convertirlo en vector fila
193193+ Dist = Dist_D(:,1);
194194+ Drec = Dist_D(:,2);
195195+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
196196+ % (Ures)
197197+ [Dcoef,Dres]=fit(Dist,Drec,'power1');
198198+ Dplot=Dcoef.a*Distplot.^Dcoef.b;
199199+200200+ %% Curva del campo early
201201+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
202202+ % asociado
203203+ Dist_E = sortrows([Distancia',Eneto']);
204204+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
205205+ % distancias iguales y elimina el duplicado
206206+ [C,~,idx] = unique(Dist_E(:,1),'stable');
207207+ val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
208208+ Dist_E = [C,val];
209209+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
210210+ % receptor mas cercano
211211+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
212212+ %Dist_U = [[0;V0_0toVal]';Dist_U];
213213+ % Separar los valores para graficar y convertirlo en vector fila
214214+ Dist = Dist_E(:,1);
215215+ Erec = Dist_E(:,2);
216216+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
217217+ % (Ures)
218218+ [Ecoef,Eres]=fit(Dist,Erec,'power1');
219219+ Eplot=Ecoef.a*Distplot.^Ecoef.b;
220220+221221+ % Para no mostrar errores cuando se repite el calculo de coeficientes
222222+ warning ('off','all');
223223+224224+ %% Calculo de coeficiente para el campo directo
225225+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
226226+ try % Intenta el calculo con puntos de inicio random
227227+ opD = fitoptions('Method','NonlinearLeastSquares',...
228228+ 'Robust','LAR',...
229229+ 'Lower',[0,0],... % Minimo valor de los coeficientes
230230+ 'Upper',[20,20],... % Maximo valor de los coeficientes
231231+ 'MaxFunEvals',3000,...
232232+ 'MaxIter',3000,...
233233+ 'TolFun',10^-3);
234234+ fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',...
235235+ 'dependent',{'y'},...
236236+ 'independent',{'dist'},...
237237+ 'problem', {'Q','W','Fac'},...
238238+ 'coefficients',{'Cd'},...
239239+ 'options',opD);
240240+ [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac});
241241+ break;
242242+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
243243+ if ii==str2double(get(handles.numIntentos,'string'))
244244+ hold off
245245+ ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error');
246246+ set(ed, 'WindowStyle', 'modal');
247247+ uiwait(ed);
248248+ return;
249249+ end
250250+ end
251251+ end
252252+253253+254254+ %% Calculo de coeficientes epsilon y Cl para campo late
255255+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
256256+ try % Intenta el calculo con puntos de inicio random
257257+ fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',...
258258+ 'dependent',{'y'},...
259259+ 'independent',{'dist'},...
260260+ 'problem', {'W','S','alpha','t','T','c','Fac'},...
261261+ 'coefficients',{'el','Cl'});
262262+ [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac});
263263+ break;
264264+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
265265+ if ii==str2double(get(handles.numIntentos,'string'))
266266+ hold off
267267+ ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error');
268268+ set(ed, 'WindowStyle', 'modal');
269269+ uiwait(ed);
270270+ return;
271271+ end
272272+ end
273273+ end
274274+275275+ %% Calculo de coeficientes epsilon y Ce para campo early
276276+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
277277+ try % Intenta el calculo con puntos de inicio random
278278+ opE = fitoptions('Method','NonlinearLeastSquares',...
279279+ 'Robust','LAR',...
280280+ 'MaxFunEvals',3000,...
281281+ 'MaxIter',3000,...
282282+ 'TolFun',10^-3);
283283+ fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',...
284284+ 'dependent',{'y'},...
285285+ 'independent',{'dist'},...
286286+ 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},...
287287+ 'coefficients',{'ee','Ce'},...
288288+ 'options',opE);
289289+ [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl});
290290+ break;
291291+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
292292+ if ii==str2double(get(handles.numIntentos,'string'))
293293+ hold off
294294+ ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error');
295295+ set(ed, 'WindowStyle', 'modal');
296296+ uiwait(ed);
297297+ return;
298298+ end
299299+ end
300300+ end
301301+ warning ('on','all');
302302+303303+ PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd));
304304+ Peplot = 10*log10(Fac *(...
305305+ (4*W)./(S*(-log(1-alpha))*Distplot) .* ...
306306+ (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl)));
307307+ Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10));
308308+ Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl);
309309+310310+ Curv(2) = plot(Distplot,Pdeplot - Plateplot,'-.r','LineWidth',1);
311311+312312+ % Leyendas
313313+ leyenda{2} = sprintf('C_{%s} - Te�rico',num2str(Rango));
314314+315315+end
316316+317317+lgdw=legend(Curv,leyenda);
318318+lgdw.FontSize = 11;
319319+%lgdw.Location = 'northeastoutside';
320320+% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya
321321+% que no es compatible
322322+if ~verLessThan('matlab','8.7')
323323+ title(lgdw,'Curvas')
324324+end
325325+ylabel(sprintf('C_{%s} (dB)',num2str(Rango)))
326326+xlabel('Distancia (m)')
327327+title({sprintf('C_{%s}',num2str(Rango));...
328328+ ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]});
329329+330330+hold off
331331+
+330
include/representarDt.m
···11+function representarDt(hObject,handles)
22+% Reprsentacion del parametro definicion
33+axes(handles.plotfig)
44+Rango = handles.Rango;
55+SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar
66+SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas
77+Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor
88+Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas
99+Fuente = string(handles.SPLm(:,2)');
1010+Receptor = string(handles.SPLm(:,3)');
1111+1212+1313+% Comprobar que bandas de frecuencias se han elegido
1414+Bandas = [];
1515+fsel = [];
1616+if handles.frec125.Value==1
1717+ Bandas = [Bandas,1];
1818+ fsel = [fsel,125];
1919+end
2020+if handles.frec250.Value==1
2121+ Bandas = [Bandas,2];
2222+ fsel = [fsel,250];
2323+end
2424+if handles.frec500.Value==1
2525+ Bandas = [Bandas,3];
2626+ fsel = [fsel,500];
2727+end
2828+if handles.frec1000.Value==1
2929+ Bandas = [Bandas,4];
3030+ fsel = [fsel,1000];
3131+end
3232+if handles.frec2000.Value==1
3333+ Bandas = [Bandas,5];
3434+ fsel = [fsel,2000];
3535+end
3636+if handles.frec4000.Value==1
3737+ Bandas = [Bandas,6];
3838+ fsel = [fsel,4000];
3939+end
4040+if handles.frec8000.Value==1
4141+ Bandas = [Bandas,7];
4242+ fsel = [fsel,8000];
4343+end
4444+if isempty(Bandas); Bandas = 1:7; end
4545+if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end
4646+4747+%% Procesado de datos
4848+% Separacion e integracion de los niveles antes y despues del rango
4949+Dneto = zeros(1,numel(SPLm));
5050+Eneto = zeros(1,numel(SPLm));
5151+Lneto = zeros(1,numel(SPLm));
5252+for i=1:numel(SPLm)
5353+ % Direct - Early - Late EXTRACTION
5454+ Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms
5555+ Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion
5656+ Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito
5757+5858+ % Ponderacion A
5959+ % f = fsel; % Frecuencias seleccionadas
6060+ % ponderacionA = 20*log10(...
6161+ % 12194^2*f.^4 ./...
6262+ % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2;
6363+ % Dbruto = Dbruto + ponderacionA;
6464+ % Ebruto = Ebruto + ponderacionA;
6565+ % Lbruto = Lbruto + ponderacionA;
6666+6767+ % Suma de niveles para los dos rangos
6868+ Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10)));
6969+ Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10)));
7070+ Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10)));
7171+end
7272+7373+% Campo util es la suma del campo directo y el early
7474+Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10));
7575+7676+%% Representacion grafica del campo Util y el Perjudicial
7777+7878+%% Puntos y curva de 0ms a Valor
7979+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
8080+% asociado
8181+Dist_U = sortrows([Distancia',Uneto']);
8282+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
8383+% distancias iguales y elimina el duplicado
8484+[C,~,idx] = unique(Dist_U(:,1),'stable');
8585+val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
8686+Dist_U = [C,val];
8787+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
8888+% receptor mas cercano
8989+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
9090+%Dist_U = [[0;V0_0toVal]';Dist_U];
9191+% Separar los valores para graficar y convertirlo en vector fila
9292+Dist = Dist_U(:,1);
9393+Urec = Dist_U(:,2);
9494+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
9595+% (Ures)
9696+[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1');
9797+Uplot=Ucoef.a*Distplot.^Ucoef.b;
9898+9999+100100+101101+%% Puntos y curva de valor a infinito ms
102102+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
103103+% asociado
104104+Dist_P = sortrows([Distancia',Lneto']);
105105+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
106106+% distancias iguales y elimina el duplicado
107107+[C,~,idx] = unique(Dist_P(:,1),'stable');
108108+val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
109109+Dist_P = [C,val];
110110+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
111111+% receptor mas cercano
112112+%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap');
113113+%Dist_P = [[0;V0_0toVal]';Dist_P];
114114+% Separar los valores para graficar y convertirlo en vector fila
115115+Dist = Dist_P(:,1);
116116+Prec = Dist_P(:,2);
117117+% Obtener coeificentes curva polinomica de grado 1
118118+[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1');
119119+% Crea la curva
120120+Pplot = Pcoef.p1*Distplot+Pcoef.p2;
121121+122122+123123+% Claridad EASE
124124+% Muestra los puntos
125125+plot(Dist,10.^(Urec/10)./( 10.^(Urec/10) + 10.^(Prec/10) ),'^b','MarkerFaceColor','b'),hold on
126126+% Muestra la curva
127127+Curv(1)=plot(Distplot,10.^(Uplot/10)./( 10.^(Uplot/10) + 10.^(Pplot/10) ),'b','LineWidth',1.2);
128128+129129+% A�ade las rejillas de las graficas
130130+grid on
131131+grid minor
132132+133133+% Leyenda
134134+leyenda{1} = sprintf('D_{%s} - EASE',num2str(Rango));
135135+136136+%% Teoria corregida
137137+% Si se ha marcado el calculo de la teoria revisada corregida se calcula y
138138+% se a�ade a la grafica
139139+if get(handles.teoriacorregida,'value')==1
140140+ %%% PARAMETROS
141141+ % Nivel de presion total de la fuente a 1 metro
142142+ SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10)));
143143+ % Volumen (m3)
144144+ V = handles.SPLm{handles.Index,15};
145145+ % Superficie (m2)
146146+ S = handles.SPLm{handles.Index,16};
147147+ % Mean Free Path
148148+ mfp = 4*V/S;
149149+ % Absorcion media
150150+ alpha = mean(handles.SPLm{handles.Index,11});
151151+ % Absorci�n equivalente de Eyring
152152+ A = -S*log(1-alpha);
153153+ % Temperatura de la sala
154154+ temp = handles.SPLm{handles.Index,17};
155155+ % Velocidad del sonido
156156+ c = 331.4 + 0.6*temp;
157157+ % Densidad del aire. Presion Atm / (constante gas*Temp
158158+ % absoluta)
159159+ rho = 101325 / (287.058*(273.15+temp));
160160+ % Impedancia acustica del aire
161161+ Z = rho*c;
162162+ % Presion de referencia
163163+ pref = 2*10^(-5);
164164+ % Factor de conversion
165165+ Fac = Z/(pref^2);
166166+ % Directividad de la fuente
167167+ Q = str2double(get(handles.Qdir,'string'));
168168+ % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1
169169+ SWL = SPL - 10*log10(1/(4*pi*1));
170170+ % Potencia de la fuente en vatios
171171+ W = 10.^(SWL/10)*10^-12;
172172+ % Tiempo de reverberacion de Eyring
173173+ T = 6*log(10)/c * mfp * 1/(-log(1-alpha));
174174+ % Rango de integracion temporal (s)
175175+ t = handles.Rango * 10^(-3);
176176+177177+ %% Obtencion de la curvas directo y early
178178+ %% Curva del campo directo
179179+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
180180+ % asociado
181181+ Dist_D = sortrows([Distancia',Dneto']);
182182+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
183183+ % distancias iguales y elimina el duplicado
184184+ [C,~,idx] = unique(Dist_D(:,1),'stable');
185185+ val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
186186+ Dist_D = [C,val];
187187+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
188188+ % receptor mas cercano
189189+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
190190+ %Dist_U = [[0;V0_0toVal]';Dist_U];
191191+ % Separar los valores para graficar y convertirlo en vector fila
192192+ Dist = Dist_D(:,1);
193193+ Drec = Dist_D(:,2);
194194+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
195195+ % (Ures)
196196+ [Dcoef,Dres]=fit(Dist,Drec,'power1');
197197+ Dplot=Dcoef.a*Distplot.^Dcoef.b;
198198+199199+ %% Curva del campo early
200200+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
201201+ % asociado
202202+ Dist_E = sortrows([Distancia',Eneto']);
203203+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
204204+ % distancias iguales y elimina el duplicado
205205+ [C,~,idx] = unique(Dist_E(:,1),'stable');
206206+ val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
207207+ Dist_E = [C,val];
208208+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
209209+ % receptor mas cercano
210210+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
211211+ %Dist_U = [[0;V0_0toVal]';Dist_U];
212212+ % Separar los valores para graficar y convertirlo en vector fila
213213+ Dist = Dist_E(:,1);
214214+ Erec = Dist_E(:,2);
215215+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
216216+ % (Ures)
217217+ [Ecoef,Eres]=fit(Dist,Erec,'power1');
218218+ Eplot=Ecoef.a*Distplot.^Ecoef.b;
219219+220220+ % Para no mostrar errores cuando se repite el calculo de coeficientes
221221+ warning ('off','all');
222222+223223+ %% Calculo de coeficiente para el campo directo
224224+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
225225+ try % Intenta el calculo con puntos de inicio random
226226+ opD = fitoptions('Method','NonlinearLeastSquares',...
227227+ 'Robust','LAR',...
228228+ 'Lower',[0,0],... % Minimo valor de los coeficientes
229229+ 'Upper',[20,20],... % Maximo valor de los coeficientes
230230+ 'MaxFunEvals',3000,...
231231+ 'MaxIter',3000,...
232232+ 'TolFun',10^-3);
233233+ fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',...
234234+ 'dependent',{'y'},...
235235+ 'independent',{'dist'},...
236236+ 'problem', {'Q','W','Fac'},...
237237+ 'coefficients',{'Cd'},...
238238+ 'options',opD);
239239+ [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac});
240240+ break;
241241+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
242242+ if ii==str2double(get(handles.numIntentos,'string'))
243243+ hold off
244244+ ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error');
245245+ set(ed, 'WindowStyle', 'modal');
246246+ uiwait(ed);
247247+ return;
248248+ end
249249+ end
250250+ end
251251+252252+253253+ %% Calculo de coeficientes epsilon y Cl para campo late
254254+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
255255+ try % Intenta el calculo con puntos de inicio random
256256+ fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',...
257257+ 'dependent',{'y'},...
258258+ 'independent',{'dist'},...
259259+ 'problem', {'W','S','alpha','t','T','c','Fac'},...
260260+ 'coefficients',{'el','Cl'});
261261+ [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac});
262262+ break;
263263+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
264264+ if ii==str2double(get(handles.numIntentos,'string'))
265265+ hold off
266266+ ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error');
267267+ set(ed, 'WindowStyle', 'modal');
268268+ uiwait(ed);
269269+ return;
270270+ end
271271+ end
272272+ end
273273+274274+ %% Calculo de coeficientes epsilon y Ce para campo early
275275+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
276276+ try % Intenta el calculo con puntos de inicio random
277277+ opE = fitoptions('Method','NonlinearLeastSquares',...
278278+ 'Robust','LAR',...
279279+ 'MaxFunEvals',3000,...
280280+ 'MaxIter',3000,...
281281+ 'TolFun',10^-3);
282282+ fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',...
283283+ 'dependent',{'y'},...
284284+ 'independent',{'dist'},...
285285+ 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},...
286286+ 'coefficients',{'ee','Ce'},...
287287+ 'options',opE);
288288+ [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl});
289289+ break;
290290+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
291291+ if ii==str2double(get(handles.numIntentos,'string'))
292292+ hold off
293293+ ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error');
294294+ set(ed, 'WindowStyle', 'modal');
295295+ uiwait(ed);
296296+ return;
297297+ end
298298+ end
299299+ end
300300+ warning ('on','all');
301301+302302+ PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd));
303303+ Peplot = 10*log10(Fac *(...
304304+ (4*W)./(S*(-log(1-alpha))*Distplot) .* ...
305305+ (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl)));
306306+ Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10));
307307+ Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl);
308308+309309+ Curv(2) = plot(Distplot,10.^(Pdeplot/10)./( 10.^(Pdeplot/10) + 10.^(Plateplot/10) ),'-.r','LineWidth',1);
310310+311311+ % Leyendas
312312+ leyenda{2} = sprintf('D_{%s} - Te�rico',num2str(Rango));
313313+314314+end
315315+316316+lgdw=legend(Curv,leyenda);
317317+lgdw.FontSize = 11;
318318+%lgdw.Location = 'northeastoutside';
319319+% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya
320320+% que no es compatible
321321+if ~verLessThan('matlab','8.7')
322322+ title(lgdw,'Curvas')
323323+end
324324+ylabel(sprintf('D_{%s} (dB)',num2str(Rango)))
325325+xlabel('Distancia (m)')
326326+title({sprintf('D_{%s}',num2str(Rango));...
327327+ ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]});
328328+329329+hold off
330330+
+30
include/representarEcograma.m
···11+function representarEcograma(handles)
22+33+axes(handles.plotfig)
44+Index = handles.Index;
55+SPLm = handles.SPLm(:,1);
66+SPLmTot = handles.SPLm(:,19);
77+Distancia = cell2mat(handles.SPLm(:,6))';
88+Fuente = string(handles.SPLm(:,2)');
99+Receptor = string(handles.SPLm(:,3)');
1010+1111+1212+% Obtener ecograma del receptor Index, sumando las octavas
1313+Ecogra = 10*log10(sum(10.^((SPLmTot{Index}(:,2:end)')/10)));
1414+tiempo = SPLmTot{Index}(:,1);
1515+1616+1717+1818+%% Representacion grafica
1919+2020+2121+% Ecograma
2222+stem(tiempo,Ecogra,'Marker','none')
2323+2424+title({sprintf('Ecograma del receptor: %s',Receptor(Index));...
2525+ ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]})
2626+xlabel('Tiempo (ms)')
2727+ylabel('Nivel SPL (dB)')
2828+% Limite del eje x con margen a ambos lados
2929+xlim([-max(tiempo)/10,max(tiempo)+max(tiempo)/10])
3030+end
+367
include/representarG.m
···11+function representarG(hObject,handles)
22+% Reprsentacion del parametro sonoridad
33+44+axes(handles.plotfig)
55+Rango = handles.Rango;
66+SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar
77+SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas
88+Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor
99+Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas
1010+Fuente = string(handles.SPLm(:,2)');
1111+Receptor = string(handles.SPLm(:,3)');
1212+1313+1414+% Comprobar que bandas de frecuencias se han elegido
1515+Bandas = [];
1616+fsel = [];
1717+if handles.frec125.Value==1
1818+ Bandas = [Bandas,1];
1919+ fsel = [fsel,125];
2020+end
2121+if handles.frec250.Value==1
2222+ Bandas = [Bandas,2];
2323+ fsel = [fsel,250];
2424+end
2525+if handles.frec500.Value==1
2626+ Bandas = [Bandas,3];
2727+ fsel = [fsel,500];
2828+end
2929+if handles.frec1000.Value==1
3030+ Bandas = [Bandas,4];
3131+ fsel = [fsel,1000];
3232+end
3333+if handles.frec2000.Value==1
3434+ Bandas = [Bandas,5];
3535+ fsel = [fsel,2000];
3636+end
3737+if handles.frec4000.Value==1
3838+ Bandas = [Bandas,6];
3939+ fsel = [fsel,4000];
4040+end
4141+if handles.frec8000.Value==1
4242+ Bandas = [Bandas,7];
4343+ fsel = [fsel,8000];
4444+end
4545+if isempty(Bandas); Bandas = 1:7; end
4646+if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end
4747+4848+%% Procesado de datos
4949+% Separacion e integracion de los niveles antes y despues del rango
5050+Dneto = zeros(1,numel(SPLm));
5151+Eneto = zeros(1,numel(SPLm));
5252+Lneto = zeros(1,numel(SPLm));
5353+for i=1:numel(SPLm)
5454+ % Direct - Early - Late EXTRACTION
5555+ Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms
5656+ Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion
5757+ Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito
5858+5959+ % Ponderacion A
6060+ % f = fsel; % Frecuencias seleccionadas
6161+ % ponderacionA = 20*log10(...
6262+ % 12194^2*f.^4 ./...
6363+ % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2;
6464+ % Dbruto = Dbruto + ponderacionA;
6565+ % Ebruto = Ebruto + ponderacionA;
6666+ % Lbruto = Lbruto + ponderacionA;
6767+6868+ % Suma de niveles para los dos rangos
6969+ Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10)));
7070+ Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10)));
7171+ Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10)));
7272+end
7373+7474+% Campo util es la suma del campo directo y el early
7575+Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10));
7676+7777+% Temperatura
7878+temp = handles.SPLm{handles.Index,17};
7979+% Velocidad del sonido
8080+c = 331.4 + 0.6*temp;
8181+% Densidad del aire. Presion Atm / (constante gas*Temp
8282+% absoluta)
8383+rho = 101325 / (287.058*(273.15+temp));
8484+% Impedancia acustica del aire
8585+Z = rho*c;
8686+% Nivel de presion total de la fuente a 1 metro
8787+SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10)));
8888+% Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1
8989+SWL = SPL - 10*log10(1/(4*pi*1));
9090+% Potencia de la fuente en vatios
9191+W = 10.^(SWL/10)*10^-12;
9292+9393+%% Representacion grafica del campo Util y el Perjudicial
9494+9595+%% Puntos y curva de 0ms a Valor
9696+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
9797+% asociado
9898+Dist_U = sortrows([Distancia',Uneto']);
9999+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
100100+% distancias iguales y elimina el duplicado
101101+[C,~,idx] = unique(Dist_U(:,1),'stable');
102102+val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
103103+Dist_U = [C,val];
104104+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
105105+% receptor mas cercano
106106+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
107107+%Dist_U = [[0;V0_0toVal]';Dist_U];
108108+% Separar los valores para graficar y convertirlo en vector fila
109109+Dist = Dist_U(:,1);
110110+Urec = Dist_U(:,2);
111111+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
112112+% (Ures)
113113+[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1');
114114+Uplot=Ucoef.a*Distplot.^Ucoef.b;
115115+116116+117117+%% Curva del campo directo
118118+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
119119+% asociado
120120+Dist_D = sortrows([Distancia',Dneto']);
121121+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
122122+% distancias iguales y elimina el duplicado
123123+[C,~,idx] = unique(Dist_D(:,1),'stable');
124124+val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
125125+Dist_D = [C,val];
126126+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
127127+% receptor mas cercano
128128+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
129129+%Dist_U = [[0;V0_0toVal]';Dist_U];
130130+% Separar los valores para graficar y convertirlo en vector fila
131131+Dist = Dist_D(:,1);
132132+Drec = Dist_D(:,2);
133133+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
134134+% (Ures)
135135+[Dcoef,Dres]=fit(Dist,Drec,'power1');
136136+Dplot=Dcoef.a*Distplot.^Dcoef.b;
137137+138138+%% Puntos y curva de valor a infinito ms
139139+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
140140+% asociado
141141+Dist_P = sortrows([Distancia',Lneto']);
142142+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
143143+% distancias iguales y elimina el duplicado
144144+[C,~,idx] = unique(Dist_P(:,1),'stable');
145145+val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
146146+Dist_P = [C,val];
147147+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
148148+% receptor mas cercano
149149+%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap');
150150+%Dist_P = [[0;V0_0toVal]';Dist_P];
151151+% Separar los valores para graficar y convertirlo en vector fila
152152+Dist = Dist_P(:,1);
153153+Prec = Dist_P(:,2);
154154+% Obtener coeificentes curva polinomica de grado 1
155155+[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1');
156156+% Crea la curva
157157+Pplot = Pcoef.p1*Distplot+Pcoef.p2;
158158+159159+160160+% Claridad EASE
161161+% Muestra los puntos
162162+plot(Dist,10*log10( (10.^(Urec/10) + 10.^(Prec/10)) ./ 10^((Dcoef.a*10^Dcoef.b)/10) ) ,'^b','MarkerFaceColor','b'),hold on
163163+% Muestra la curva
164164+Curv(1)=plot(Distplot,10*log10( (10.^(Uplot/10) + 10.^(Pplot/10)) ./ 10^((Dcoef.a*10^Dcoef.b)/10) ),'b','LineWidth',1.2);
165165+166166+% A�ade las rejillas de las graficas
167167+grid on
168168+grid minor
169169+170170+% Leyenda
171171+leyenda{1} = 'G - EASE';
172172+173173+%% Teoria corregida
174174+% Si se ha marcado el calculo de la teoria revisada corregida se calcula y
175175+% se a�ade a la grafica
176176+if get(handles.teoriacorregida,'value')==1
177177+ %%% PARAMETROS
178178+ % Nivel de presion total de la fuente a 1 metro
179179+ SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10)));
180180+ % Volumen (m3)
181181+ V = handles.SPLm{handles.Index,15};
182182+ % Superficie (m2)
183183+ S = handles.SPLm{handles.Index,16};
184184+ % Mean Free Path
185185+ mfp = 4*V/S;
186186+ % Absorcion media
187187+ alpha = mean(handles.SPLm{handles.Index,11});
188188+ % Absorci�n equivalente de Eyring
189189+ A = -S*log(1-alpha);
190190+ % Temperatura de la sala
191191+ temp = handles.SPLm{handles.Index,17};
192192+ % Velocidad del sonido
193193+ c = 331.4 + 0.6*temp;
194194+ % Densidad del aire. Presion Atm / (constante gas*Temp
195195+ % absoluta)
196196+ rho = 101325 / (287.058*(273.15+temp));
197197+ % Impedancia acustica del aire
198198+ Z = rho*c;
199199+ % Presion de referencia
200200+ pref = 2*10^(-5);
201201+ % Factor de conversion
202202+ Fac = Z/(pref^2);
203203+ % Directividad de la fuente
204204+ Q = str2double(get(handles.Qdir,'string'));
205205+ % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1
206206+ SWL = SPL - 10*log10(1/(4*pi*1));
207207+ % Potencia de la fuente en vatios
208208+ W = 10.^(SWL/10)*10^-12;
209209+ % Tiempo de reverberacion de Eyring
210210+ T = 6*log(10)/c * mfp * 1/(-log(1-alpha));
211211+ % Rango de integracion temporal (s)
212212+ t = handles.Rango * 10^(-3);
213213+214214+ %% Obtencion de la curvas directo y early
215215+ %% Curva del campo directo
216216+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
217217+ % asociado
218218+ Dist_D = sortrows([Distancia',Dneto']);
219219+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
220220+ % distancias iguales y elimina el duplicado
221221+ [C,~,idx] = unique(Dist_D(:,1),'stable');
222222+ val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
223223+ Dist_D = [C,val];
224224+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
225225+ % receptor mas cercano
226226+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
227227+ %Dist_U = [[0;V0_0toVal]';Dist_U];
228228+ % Separar los valores para graficar y convertirlo en vector fila
229229+ Dist = Dist_D(:,1);
230230+ Drec = Dist_D(:,2);
231231+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
232232+ % (Ures)
233233+ [Dcoef,Dres]=fit(Dist,Drec,'power1');
234234+ Dplot=Dcoef.a*Distplot.^Dcoef.b;
235235+236236+ %% Curva del campo early
237237+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
238238+ % asociado
239239+ Dist_E = sortrows([Distancia',Eneto']);
240240+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
241241+ % distancias iguales y elimina el duplicado
242242+ [C,~,idx] = unique(Dist_E(:,1),'stable');
243243+ val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
244244+ Dist_E = [C,val];
245245+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
246246+ % receptor mas cercano
247247+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
248248+ %Dist_U = [[0;V0_0toVal]';Dist_U];
249249+ % Separar los valores para graficar y convertirlo en vector fila
250250+ Dist = Dist_E(:,1);
251251+ Erec = Dist_E(:,2);
252252+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
253253+ % (Ures)
254254+ [Ecoef,Eres]=fit(Dist,Erec,'power1');
255255+ Eplot=Ecoef.a*Distplot.^Ecoef.b;
256256+257257+ % Para no mostrar errores cuando se repite el calculo de coeficientes
258258+ warning ('off','all');
259259+260260+ %% Calculo de coeficiente para el campo directo
261261+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
262262+ try % Intenta el calculo con puntos de inicio random
263263+ opD = fitoptions('Method','NonlinearLeastSquares',...
264264+ 'Robust','LAR',...
265265+ 'Lower',[0,0],... % Minimo valor de los coeficientes
266266+ 'Upper',[20,20],... % Maximo valor de los coeficientes
267267+ 'MaxFunEvals',3000,...
268268+ 'MaxIter',3000,...
269269+ 'TolFun',10^-3);
270270+ fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',...
271271+ 'dependent',{'y'},...
272272+ 'independent',{'dist'},...
273273+ 'problem', {'Q','W','Fac'},...
274274+ 'coefficients',{'Cd'},...
275275+ 'options',opD);
276276+ [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac});
277277+ break;
278278+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
279279+ if ii==str2double(get(handles.numIntentos,'string'))
280280+ hold off
281281+ ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error');
282282+ set(ed, 'WindowStyle', 'modal');
283283+ uiwait(ed);
284284+ return;
285285+ end
286286+ end
287287+ end
288288+289289+290290+ %% Calculo de coeficientes epsilon y Cl para campo late
291291+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
292292+ try % Intenta el calculo con puntos de inicio random
293293+ fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',...
294294+ 'dependent',{'y'},...
295295+ 'independent',{'dist'},...
296296+ 'problem', {'W','S','alpha','t','T','c','Fac'},...
297297+ 'coefficients',{'el','Cl'});
298298+ [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac});
299299+ break;
300300+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
301301+ if ii==str2double(get(handles.numIntentos,'string'))
302302+ hold off
303303+ ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error');
304304+ set(ed, 'WindowStyle', 'modal');
305305+ uiwait(ed);
306306+ return;
307307+ end
308308+ end
309309+ end
310310+311311+ %% Calculo de coeficientes epsilon y Ce para campo early
312312+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
313313+ try % Intenta el calculo con puntos de inicio random
314314+ opE = fitoptions('Method','NonlinearLeastSquares',...
315315+ 'Robust','LAR',...
316316+ 'MaxFunEvals',3000,...
317317+ 'MaxIter',3000,...
318318+ 'TolFun',10^-3);
319319+ fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',...
320320+ 'dependent',{'y'},...
321321+ 'independent',{'dist'},...
322322+ 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},...
323323+ 'coefficients',{'ee','Ce'},...
324324+ 'options',opE);
325325+ [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl});
326326+ break;
327327+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
328328+ if ii==str2double(get(handles.numIntentos,'string'))
329329+ hold off
330330+ ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error');
331331+ set(ed, 'WindowStyle', 'modal');
332332+ uiwait(ed);
333333+ return;
334334+ end
335335+ end
336336+ end
337337+ warning ('on','all');
338338+339339+ PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd));
340340+ Peplot = 10*log10(Fac *(...
341341+ (4*W)./(S*(-log(1-alpha))*Distplot) .* ...
342342+ (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl)));
343343+ Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10));
344344+ Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl);
345345+346346+ Curv(2) = plot(Distplot,10*log10( (10.^(Pdeplot/10) + 10.^(Plateplot/10)) ./ (Fac * ( W./(4*pi*10.^2)*fitiD.Cd)) ),'-.r','LineWidth',1);
347347+348348+ % Leyendas
349349+ leyenda{2} = 'G - Te�rico';
350350+351351+end
352352+353353+lgdw=legend(Curv,leyenda);
354354+lgdw.FontSize = 11;
355355+%lgdw.Location = 'northeastoutside';
356356+% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya
357357+% que no es compatible
358358+if ~verLessThan('matlab','8.7')
359359+ title(lgdw,'Curvas')
360360+end
361361+ylabel('G (dB)')
362362+xlabel('Distancia (m)')
363363+title({'G';...
364364+ ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]});
365365+366366+hold off
367367+
+436
include/representarSPLvsDist2.m
···11+function representarSPLvsDist2(hObject,handles)
22+33+axes(handles.plotfig)
44+Rango = handles.Rango;
55+SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar
66+SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas
77+Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor
88+Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas
99+Fuente = string(handles.SPLm(:,2)');
1010+Receptor = string(handles.SPLm(:,3)');
1111+1212+1313+% Comprobar que bandas de frecuencias se han elegido
1414+Bandas = [];
1515+fsel = [];
1616+if handles.frec125.Value==1
1717+ Bandas = [Bandas,1];
1818+ fsel = [fsel,125];
1919+end
2020+if handles.frec250.Value==1
2121+ Bandas = [Bandas,2];
2222+ fsel = [fsel,250];
2323+end
2424+if handles.frec500.Value==1
2525+ Bandas = [Bandas,3];
2626+ fsel = [fsel,500];
2727+end
2828+if handles.frec1000.Value==1
2929+ Bandas = [Bandas,4];
3030+ fsel = [fsel,1000];
3131+end
3232+if handles.frec2000.Value==1
3333+ Bandas = [Bandas,5];
3434+ fsel = [fsel,2000];
3535+end
3636+if handles.frec4000.Value==1
3737+ Bandas = [Bandas,6];
3838+ fsel = [fsel,4000];
3939+end
4040+if handles.frec8000.Value==1
4141+ Bandas = [Bandas,7];
4242+ fsel = [fsel,8000];
4343+end
4444+if isempty(Bandas); Bandas = 1:7; end
4545+if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end
4646+4747+%% Procesado de datos
4848+% Separacion e integracion de los niveles antes y despues del rango
4949+Dneto = zeros(1,numel(SPLm));
5050+Eneto = zeros(1,numel(SPLm));
5151+Lneto = zeros(1,numel(SPLm));
5252+for i=1:numel(SPLm)
5353+ % Direct - Early - Late EXTRACTION
5454+ Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 1 ms
5555+ Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 1 ms a tiempo de integracion
5656+ Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito
5757+5858+ % Ponderacion A
5959+ % f = fsel; % Frecuencias seleccionadas
6060+ % ponderacionA = 20*log10(...
6161+ % 12194^2*f.^4 ./...
6262+ % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2;
6363+ % Dbruto = Dbruto + ponderacionA;
6464+ % Ebruto = Ebruto + ponderacionA;
6565+ % Lbruto = Lbruto + ponderacionA;
6666+6767+ % Suma de niveles para los dos rangos
6868+ Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10)));
6969+ Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10)));
7070+ Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10)));
7171+end
7272+7373+% Campo util es la suma del campo directo y el early
7474+Uneto = 10*log10(10.^(Dneto/10)+10.^(Eneto/10));
7575+7676+%% Representacion grafica del campo Util y el Perjudicial
7777+colores = colormap(jet(21));
7878+% Indices de color
7979+iCU = 1;
8080+iCUt = 3;
8181+iCL = 18;
8282+iCLt = 21;
8383+%% Puntos y curva de 0ms a Valor
8484+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
8585+% asociado
8686+Dist_U = sortrows([Distancia',Uneto']);
8787+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
8888+% distancias iguales y elimina el duplicado
8989+[C,~,idx] = unique(Dist_U(:,1),'stable');
9090+val = accumarray(idx,Dist_U(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
9191+Dist_U = [C,val];
9292+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
9393+% receptor mas cercano
9494+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
9595+%Dist_U = [[0;V0_0toVal]';Dist_U];
9696+% Separar los valores para graficar y convertirlo en vector fila
9797+Dist = Dist_U(:,1);
9898+Urec = Dist_U(:,2);
9999+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
100100+% (Ures)
101101+[Ucoef,Ures,Uoutput]=fit(Dist,Urec,'power1');
102102+Uplot=Ucoef.a*Distplot.^Ucoef.b;
103103+% Muestra los puntos
104104+plot(Dist,Urec,'s','Color',colores(iCU,:),'MarkerFaceColor',colores(iCU,:))
105105+hold on
106106+% Muestra los errores
107107+Uerr = confint(Ucoef);
108108+Ucurvarec = Ucoef.a*Dist.^Ucoef.b;
109109+errorbar(Dist,Ucoef.a*Dist.^Ucoef.b,... % Curva
110110+ (Uerr(2)*Dist.^Uerr(4)) - Ucurvarec,... % Error positivo
111111+ Ucurvarec - (Uerr(1)*Dist.^Uerr(3)),... % Error negativo
112112+ 'b','LineStyle','none')
113113+% Muestra la curva
114114+Curv(1)=plot(Distplot,Uplot,'Color',colores(iCU,:),'LineWidth',1.2);
115115+116116+%% Puntos y curva de valor a infinito ms
117117+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
118118+% asociado
119119+Dist_P = sortrows([Distancia',Lneto']);
120120+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
121121+% distancias iguales y elimina el duplicado
122122+[C,~,idx] = unique(Dist_P(:,1),'stable');
123123+val = accumarray(idx,Dist_P(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
124124+Dist_P = [C,val];
125125+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
126126+% receptor mas cercano
127127+%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap');
128128+%Dist_P = [[0;V0_0toVal]';Dist_P];
129129+% Separar los valores para graficar y convertirlo en vector fila
130130+Dist = Dist_P(:,1);
131131+Prec = Dist_P(:,2);
132132+% Obtener coeificentes curva polinomica de grado 1
133133+[Pcoef,Pres,Poutput] = fit(Dist,Prec,'poly1');
134134+% Crea la curva
135135+Pplot = Pcoef.p1*Distplot+Pcoef.p2;
136136+% Muestra los puntos
137137+plot(Dist,Prec,'^','Color',colores(iCL,:),'MarkerFaceColor',colores(iCL,:))
138138+% Muestra los errores
139139+Perr = confint(Pcoef);
140140+Pcurvarec = Pcoef.p1*Dist+Pcoef.p2;
141141+errorbar(Dist,Pcoef.p1*Dist+Pcoef.p2,... % Curva
142142+ (Perr(2)*Dist+Perr(4)) - Pcurvarec,... % Error positivo
143143+ Pcurvarec - (Perr(1)*Dist+Perr(3)),... % Error negativo
144144+ 'r','LineStyle','none')
145145+% Muestra la curva
146146+Curv(2)=plot(Distplot,Pplot,'Color',colores(iCL,:),'LineWidth',1.2);
147147+148148+% A�ade las rejillas de las graficas
149149+grid on
150150+grid minor
151151+152152+% Obtener punto de cruce
153153+CortesInd = find(abs(Uplot-Pplot)<=(0.01));
154154+if ~isnan(CortesInd)
155155+ DistCorte = Distplot(CortesInd(1));
156156+ text(DistCorte,Uplot(CortesInd(1))+1,...
157157+ {'EASE',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorte),' m'])},...
158158+ 'VerticalAlignment','bottom','HorizontalAlignment','left')
159159+end
160160+161161+%% Guarda un .dat para generar graficas en el LaTex
162162+%guardarErrores(Ucoef,Pcoef,Distancia,Dist_P,Dist_U)
163163+%%
164164+165165+% Obtener numero de ceros decimales de las pendientes, sumarle 1 y convertir a
166166+% string, para mostrar tantos numeros decimales en las funciones que se ven en
167167+% la leyenda
168168+P11 = num2str(fix(abs(log10(abs(Ucoef.b))))+2);
169169+P21 = num2str(fix(abs(log10(abs(Pcoef.p1))))+2);
170170+171171+% Colores en formato texto para el color de las funciones
172172+ColU = [num2str(colores(iCU,1)),',',num2str(colores(iCU,2)),',',num2str(colores(iCU,3))];
173173+ColL = [num2str(colores(iCL,1)),',',num2str(colores(iCL,2)),',',num2str(colores(iCL,3))];
174174+175175+% Leyenda
176176+leyenda{1} = sprintf(['\\bf0 %s %d ms\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.2f�x^{%4.',P11,'f} \n \\color{white}.'],'a',Rango,Ures.adjrsquare,ColU,Ucoef.a,Ucoef.b);
177177+leyenda{2} = sprintf(['\\bf%d ms %s\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.',P21,'f�x+%4.2f \n \\color{white}.'],Rango,'a infinito',Pres.adjrsquare,ColL,Pcoef.p1,Pcoef.p2);
178178+179179+%% Teoria corregida
180180+% Si se ha marcado el calculo de la teoria revisada corregida se calcula y
181181+% se a�ade a la grafica
182182+if get(handles.teoriacorregida,'value')==1
183183+ %%% PARAMETROS
184184+ % Nivel de presion total de la fuente a 1 metro
185185+ SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10)));
186186+ % Volumen (m3)
187187+ V = handles.SPLm{handles.Index,15};
188188+ % Superficie (m2)
189189+ S = handles.SPLm{handles.Index,16};
190190+ % Mean Free Path
191191+ mfp = 4*V/S;
192192+ % Absorcion media
193193+ alpha = mean(handles.SPLm{handles.Index,11});
194194+ % Absorci�n equivalente de Eyring
195195+ A = -S*log(1-alpha);
196196+ % Temperatura de la sala
197197+ temp = handles.SPLm{handles.Index,17};
198198+ % Velocidad del sonido
199199+ c = 331.4 + 0.6*temp;
200200+ % Densidad del aire. Presion Atm / (constante gas*Temp
201201+ % absoluta)
202202+ rho = 101325 / (287.058*(273.15+temp));
203203+ % Impedancia acustica del aire
204204+ Z = rho*c;
205205+ % Presion de referencia
206206+ pref = 2*10^(-5);
207207+ % Factor de conversion
208208+ Fac = Z/(pref^2);
209209+ % Directividad de la fuente
210210+ Q = str2double(get(handles.Qdir,'string'));
211211+ % Nivel de potencia de la fuente (SPL a 1 metro). Se supone Q=1
212212+ SWL = SPL - 10*log10(1/(4*pi*1));
213213+ % Potencia de la fuente en vatios
214214+ W = 10.^(SWL/10)*10^-12;
215215+ % Tiempo de reverberacion de Eyring
216216+ T = 6*log(10)/c * mfp * 1/(-log(1-alpha));
217217+ % Rango de integracion temporal (s)
218218+ t = handles.Rango * 10^(-3);
219219+220220+ %% Obtencion de la curvas directo y early
221221+ %% Curva del campo directo
222222+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
223223+ % asociado
224224+ Dist_D = sortrows([Distancia',Dneto']);
225225+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
226226+ % distancias iguales y elimina el duplicado
227227+ [C,~,idx] = unique(Dist_D(:,1),'stable');
228228+ val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
229229+ Dist_D = [C,val];
230230+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
231231+ % receptor mas cercano
232232+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
233233+ %Dist_U = [[0;V0_0toVal]';Dist_U];
234234+ % Separar los valores para graficar y convertirlo en vector fila
235235+ Dist = Dist_D(:,1);
236236+ Drec = Dist_D(:,2);
237237+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
238238+ % (Ures)
239239+ [Dcoef,Dres]=fit(Dist,Drec,'power1');
240240+ Dplot=Dcoef.a*Distplot.^Dcoef.b;
241241+242242+ %% Curva del campo early
243243+ % Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
244244+ % asociado
245245+ Dist_E = sortrows([Distancia',Eneto']);
246246+ % Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
247247+ % distancias iguales y elimina el duplicado
248248+ [C,~,idx] = unique(Dist_E(:,1),'stable');
249249+ val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
250250+ Dist_E = [C,val];
251251+ % A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
252252+ % receptor mas cercano
253253+ %V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
254254+ %Dist_U = [[0;V0_0toVal]';Dist_U];
255255+ % Separar los valores para graficar y convertirlo en vector fila
256256+ Dist = Dist_E(:,1);
257257+ Erec = Dist_E(:,2);
258258+ % Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
259259+ % (Ures)
260260+ [Ecoef,Eres]=fit(Dist,Erec,'power1');
261261+ Eplot=Ecoef.a*Distplot.^Ecoef.b;
262262+263263+ % Para no mostrar errores cuando se repite el calculo de coeficientes
264264+ warning ('off','all');
265265+266266+ %% Calculo de coeficiente para el campo directo
267267+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
268268+ try % Intenta el calculo con puntos de inicio random
269269+ opD = fitoptions('Method','NonlinearLeastSquares',...
270270+ 'Robust','LAR',...
271271+ 'Lower',[0,0],... % Minimo valor de los coeficientes
272272+ 'Upper',[20,20],... % Maximo valor de los coeficientes
273273+ 'MaxFunEvals',3000,...
274274+ 'MaxIter',3000,...
275275+ 'TolFun',10^-3);
276276+ fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',...
277277+ 'dependent',{'y'},...
278278+ 'independent',{'dist'},...
279279+ 'problem', {'Q','W','Fac'},...
280280+ 'coefficients',{'Cd'},...
281281+ 'options',opD);
282282+ [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac});
283283+ break;
284284+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
285285+ if ii==str2double(get(handles.numIntentos,'string'))
286286+ hold off
287287+ ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error');
288288+ set(ed, 'WindowStyle', 'modal');
289289+ uiwait(ed);
290290+ return;
291291+ end
292292+ end
293293+ end
294294+295295+296296+ %% Calculo de coeficientes epsilon y Cl para campo late
297297+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
298298+ try % Intenta el calculo con puntos de inicio random
299299+ fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',...
300300+ 'dependent',{'y'},...
301301+ 'independent',{'dist'},...
302302+ 'problem', {'W','S','alpha','t','T','c','Fac'},...
303303+ 'coefficients',{'el','Cl'});
304304+ [fitiL,gofL,outputL] = fit(Distplot',10.^(Pplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac});
305305+ break;
306306+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
307307+ if ii==str2double(get(handles.numIntentos,'string'))
308308+ hold off
309309+ ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error');
310310+ set(ed, 'WindowStyle', 'modal');
311311+ uiwait(ed);
312312+ return;
313313+ end
314314+ end
315315+ end
316316+317317+ %% Calculo de coeficientes epsilon y Ce para campo early
318318+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
319319+ try % Intenta el calculo con puntos de inicio random
320320+ opE = fitoptions('Method','NonlinearLeastSquares',...
321321+ 'Robust','LAR',...
322322+ 'MaxFunEvals',3000,...
323323+ 'MaxIter',3000,...
324324+ 'TolFun',10^-3);
325325+ fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',...
326326+ 'dependent',{'y'},...
327327+ 'independent',{'dist'},...
328328+ 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},...
329329+ 'coefficients',{'ee','Ce'},...
330330+ 'options',opE);
331331+ [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl});
332332+ break;
333333+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
334334+ if ii==str2double(get(handles.numIntentos,'string'))
335335+ hold off
336336+ ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error');
337337+ set(ed, 'WindowStyle', 'modal');
338338+ uiwait(ed);
339339+ return;
340340+ end
341341+ end
342342+ end
343343+ warning ('on','all');
344344+345345+ PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd));
346346+ Peplot = 10*log10(Fac *(...
347347+ (4*W)./(S*(-log(1-alpha))*Distplot) .* ...
348348+ (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl)));
349349+ Pdeplot = 10*log10(10.^(PDplot/10)+10.^(Peplot/10));
350350+ Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl);
351351+352352+ Curv(3) = plot(Distplot,Pdeplot,'-.','Color',colores(iCUt,:),'LineWidth',1);
353353+ Curv(4) = plot(Distplot,Plateplot,'-.','Color',colores(iCLt,:),'LineWidth',1);
354354+355355+ % Colores en formato texto para el color de las funciones
356356+ ColUteo = [num2str(colores(iCUt,1)),',',num2str(colores(iCUt,2)),',',num2str(colores(iCUt,3))];
357357+ ColLteo = [num2str(colores(iCLt,1)),',',num2str(colores(iCLt,2)),',',num2str(colores(iCLt,3))];
358358+359359+ % Leyendas
360360+ leyenda{3} = sprintf('\\bf0 %s %d ms\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_E = %4.3f | C_E = %4.3f | R^2_{adj} = %4.2f \n C_D = %4.3f | R^2_{adj} = %4.2f \n \\color{white}.','a',Rango,ColUteo,fitiE.ee,fitiE.Ce,gofE.adjrsquare,fitiD.Cd,gofD.adjrsquare);
361361+ leyenda{4} = sprintf('\\bf%d ms %s\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_L = %4.3f | C_L = %4.3f | R^2_{adj} = %4.2f',Rango,'a infinito',ColLteo,fitiL.el,fitiL.Cl,gofL.adjrsquare);
362362+363363+364364+ % Obtener punto de cruce
365365+ CortesInd = find(abs(Pdeplot-Plateplot)<=(0.01));
366366+ if ~isnan(CortesInd)
367367+ DistCorteTeo = Distplot(CortesInd(1));
368368+ text(DistCorteTeo,Pdeplot(CortesInd(1))-1,...
369369+ {'Te�rica',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorteTeo),' m'])},...
370370+ 'VerticalAlignment','bottom','HorizontalAlignment','right')
371371+ end
372372+373373+ % Almacenar variables de interes para despues exportarlas dentro del
374374+ % .mat
375375+376376+ % Coeficientes
377377+ handles.Elate = fitiL.el;
378378+ handles.Clate = fitiL.Cl;
379379+ handles.Eearly = fitiE.ee;
380380+ handles.Cearly = fitiE.Ce;
381381+ handles.Cdirect = fitiD.Cd;
382382+383383+ % Parametros
384384+ handles.SPL = SPL; % Nivel de presion a 1 metro
385385+ handles.W = W; % Potencia
386386+ handles.Q = Q; % Directividad
387387+ handles.t = t; % Rango temporal en segundos
388388+ handles.T = T; % Tiempo de reverberaci�n de Eyring
389389+ handles.c = c; % Velocidad de sonido
390390+ handles.S = S; % Superficie
391391+ handles.V = V; % Volumen
392392+ handles.alpha = alpha; % Coeficiente de absorcion medio
393393+ handles.Z = Z; % Impedancia del aire
394394+ handles.rho = rho; % Densidad del aire
395395+ handles.A = A; % Absorcion equivalente de Eyring
396396+397397+ % Curvas
398398+ handles.Distancia = Distplot; % Vector de distancia
399399+ handles.EaseU = Uplot; % Curva del campo util (EASE)
400400+ handles.EaseP = Pplot; % Curva del campo perjudicial (EASE)
401401+ handles.TeoU = Pdeplot; % Curva del campo util (Teorico)
402402+ handles.TeoP = Plateplot; % Curva del campo perjudicial (Teorico)
403403+ handles.EaseD = Dplot; % Curva del campo directo (EASE)
404404+ handles.EaseE = Eplot; % Curva del campo early (EASE)
405405+ handles.EaseL = Pplot; % Curva del campo late (EASE)
406406+ handles.TeoD = PDplot; % Curva del campo directo (Teorico)
407407+ handles.TeoE = Peplot; % Curva del campo early (Teorico)
408408+ handles.TeoL = Plateplot; % Curva del campo late (Teorico)
409409+410410+ if exist('DistCorte','var')
411411+ handles.DistCorte = DistCorte;
412412+ end
413413+ if exist('DistCorteTeo','var')
414414+ handles.DistCorteTeo = DistCorteTeo;
415415+ end
416416+ % Actualizar variables en la aplicacion
417417+ guidata(hObject, handles);
418418+419419+end
420420+421421+lgdw=legend(Curv,leyenda);
422422+lgdw.FontSize = 11;
423423+%lgdw.Location = 'northeastoutside';
424424+% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya
425425+% que no es compatible
426426+if ~verLessThan('matlab','8.7')
427427+ title(lgdw,'Curvas')
428428+end
429429+ylabel('Nivel de presi�n ac�stica (dB)')
430430+xlabel('Distancia (m)')
431431+title({['SPL seg�n rango de tiempo',sprintf(' - %d ms',Rango)];...
432432+ ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]});
433433+434434+hold off
435435+436436+
+421
include/representarSPLvsDist3.m
···11+function representarSPLvsDist3(hObject,handles)
22+33+axes(handles.plotfig)
44+Rango = handles.Rango;
55+SPLmTot = handles.SPLm(:,19); % Matriz con los rayos sin procesar
66+SPLm = handles.SPLm(:,20); % Matriz con valores cada ms y por octavas
77+Distancia = cell2mat(handles.SPLm(:,6))'; % Vector de distancias fuente-receptor
88+Distplot = min(Distancia):0.01:max(Distancia); % Vector de distancias para las curvas
99+Fuente = string(handles.SPLm(:,2)');
1010+Receptor = string(handles.SPLm(:,3)');
1111+1212+1313+% Comprobar que bandas de frecuencias se han elegido
1414+Bandas = [];
1515+fsel = [];
1616+if handles.frec125.Value==1
1717+ Bandas = [Bandas,1];
1818+ fsel = [fsel,125];
1919+end
2020+if handles.frec250.Value==1
2121+ Bandas = [Bandas,2];
2222+ fsel = [fsel,250];
2323+end
2424+if handles.frec500.Value==1
2525+ Bandas = [Bandas,3];
2626+ fsel = [fsel,500];
2727+end
2828+if handles.frec1000.Value==1
2929+ Bandas = [Bandas,4];
3030+ fsel = [fsel,1000];
3131+end
3232+if handles.frec2000.Value==1
3333+ Bandas = [Bandas,5];
3434+ fsel = [fsel,2000];
3535+end
3636+if handles.frec4000.Value==1
3737+ Bandas = [Bandas,6];
3838+ fsel = [fsel,4000];
3939+end
4040+if handles.frec8000.Value==1
4141+ Bandas = [Bandas,7];
4242+ fsel = [fsel,8000];
4343+end
4444+if isempty(Bandas); Bandas = 1:7; end
4545+if isempty(fsel); fsel = 10^3*(2.^((-3:3))); end
4646+4747+%% Procesado de datos
4848+% Separacion e integracion de los niveles antes y despues del rango
4949+Dneto = zeros(1,numel(SPLm));
5050+Eneto = zeros(1,numel(SPLm));
5151+Lneto = zeros(1,numel(SPLm));
5252+for i=1:numel(SPLm)
5353+ % Direct - Early - Late EXTRACTION
5454+ Dbruto = SPLm{i}(1,Bandas); % Niveles de 0 a 2 ms
5555+ Ebruto = SPLm{i}(2:Rango,Bandas); % Niveles de 2 ms a tiempo de integracion
5656+ Lbruto = SPLm{i}(Rango+1:end,Bandas); % Niveles de tiempo de integracion a infinito
5757+5858+ % Ponderacion A
5959+ % f = fsel; % Frecuencias seleccionadas
6060+ % ponderacionA = 20*log10(...
6161+ % 12194^2*f.^4 ./...
6262+ % ((f.^2+20.6^2).*sqrt((f.^2+107.7^2).*(f.^2+737.9^2)).*(f.^2+12194^2)))+2;
6363+ % Dbruto = Dbruto + ponderacionA;
6464+ % Ebruto = Ebruto + ponderacionA;
6565+ % Lbruto = Lbruto + ponderacionA;
6666+6767+ % Suma de niveles para los dos rangos
6868+ Dneto(i) = 10*log10(sum(10.^(Dbruto(:)/10)));
6969+ Eneto(i) = 10*log10(sum(10.^(Ebruto(:)/10)));
7070+ Lneto(i) = 10*log10(sum(10.^(Lbruto(:)/10)));
7171+end
7272+7373+7474+7575+%% Representacion grafica del campo Directo/Early/Late
7676+colores = colormap(jet(21));
7777+% Indices de color
7878+iCD = 1;
7979+iCDt = 3;
8080+iCE = 6;
8181+iCEt = 7;
8282+iCL = 15;
8383+iCLt = 16;
8484+%% Puntos y curva del campo directo
8585+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
8686+% asociado
8787+Dist_D = sortrows([Distancia',Dneto']);
8888+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
8989+% distancias iguales y elimina el duplicado
9090+[C,~,idx] = unique(Dist_D(:,1),'stable');
9191+val = accumarray(idx,Dist_D(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
9292+Dist_D = [C,val];
9393+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
9494+% receptor mas cercano
9595+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
9696+%Dist_U = [[0;V0_0toVal]';Dist_U];
9797+% Separar los valores para graficar y convertirlo en vector fila
9898+Dist = Dist_D(:,1);
9999+Drec = Dist_D(:,2);
100100+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
101101+% (Ures)
102102+[Dcoef,Dres,Doutput]=fit(Dist,Drec,'power1');
103103+Dplot=Dcoef.a*Distplot.^Dcoef.b;
104104+% Muestra los puntos
105105+plot(Dist,Drec,'s','Color',colores(iCD,:),'MarkerFaceColor',colores(iCD,:)),hold on
106106+% Muestra los errores
107107+Derr = confint(Dcoef);
108108+Dcurvarec = Dcoef.a*Dist.^Dcoef.b;
109109+errorbar(Dist,Dcoef.a*Dist.^Dcoef.b,... % Curva
110110+ (Derr(2)*Dist.^Derr(4)) - Dcurvarec,... % Error positivo
111111+ Dcurvarec - (Derr(1)*Dist.^Derr(3)),... % Error negativo
112112+ 'Color',colores(iCD,:),'LineStyle','none')
113113+hold on
114114+% Muestra la curva
115115+Curv(1)=plot(Distplot,Dplot,'Color',colores(iCD,:),'LineWidth',1.2);
116116+117117+%% Curva del campo early
118118+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
119119+% asociado
120120+Dist_E = sortrows([Distancia',Eneto']);
121121+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
122122+% distancias iguales y elimina el duplicado
123123+[C,~,idx] = unique(Dist_E(:,1),'stable');
124124+val = accumarray(idx,Dist_E(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
125125+Dist_E = [C,val];
126126+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
127127+% receptor mas cercano
128128+%V0_0toVal=interp1(Dist_U(:,1),Dist_U(:,2),0,'linear','extrap');
129129+%Dist_U = [[0;V0_0toVal]';Dist_U];
130130+% Separar los valores para graficar y convertirlo en vector fila
131131+Dist = Dist_E(:,1);
132132+Erec = Dist_E(:,2);
133133+% Crear curva potencial. Obtiene coeficientes (Ucoef) y datos de ajuste
134134+% (Ures)
135135+[Ecoef,Eres,Eoutput]=fit(Dist,Erec,'power1');
136136+Eplot=Ecoef.a*Distplot.^Ecoef.b;
137137+% Muestra los puntos
138138+plot(Dist,Erec,'d','Color',colores(iCE,:),'MarkerFaceColor',colores(iCE,:))
139139+% Muestra los errores
140140+Eerr = confint(Ecoef);
141141+Ecurvarec = Ecoef.a*Dist.^Ecoef.b;
142142+errorbar(Dist,Ecoef.a*Dist.^Ecoef.b,... % Curva
143143+ (Eerr(2)*Dist.^Eerr(4)) - Ecurvarec,... % Error positivo
144144+ Ecurvarec - (Eerr(1)*Dist.^Eerr(3)),... % Error negativo
145145+ 'Color',colores(iCE,:),'LineStyle','none')
146146+% Muestra la curva
147147+Curv(2)=plot(Distplot,Eplot,'Color',colores(iCE,:),'LineWidth',1.2);
148148+149149+%% Puntos y curva de campor Late
150150+% Ordenar valores de distancia de menor a mayor manteniendo su valor de SPl
151151+% asociado
152152+Dist_L = sortrows([Distancia',Lneto']);
153153+% Si tiene distancias duplicadas/iguales se promedia el nivel de las dos
154154+% distancias iguales y elimina el duplicado
155155+[C,~,idx] = unique(Dist_L(:,1),'stable');
156156+val = accumarray(idx,Dist_L(:,2),[],@(x) 10*log10(mean(10.^(x/10))));
157157+Dist_L = [C,val];
158158+% A�adir por extrapolacion valor en la posicion de 0 metros hasta la posicion del
159159+% receptor mas cercano
160160+%V0_0toVal=interp1(Dist_P(:,1),Dist_P(:,2),0,'linear','extrap');
161161+%Dist_P = [[0;V0_0toVal]';Dist_P];
162162+% Separar los valores para graficar y convertirlo en vector fila
163163+Dist = Dist_L(:,1);
164164+Lrec = Dist_L(:,2);
165165+% Obtener coeificentes curva polinomica de grado 1
166166+[Lcoef,Lres,Poutput] = fit(Dist,Lrec,'poly1');
167167+% Crea la curva
168168+Lplot = Lcoef.p1*Distplot+Lcoef.p2;
169169+% Muestra los puntos
170170+plot(Dist,Lrec,'^','Color',colores(iCL,:),'MarkerFaceColor',colores(iCL,:))
171171+% Muestra los errores
172172+Lerr = confint(Lcoef);
173173+Lcurvarec = Lcoef.p1*Dist+Lcoef.p2;
174174+errorbar(Dist,Lcoef.p1*Dist+Lcoef.p2,... % Curva
175175+ (Lerr(2)*Dist+Lerr(4)) - Lcurvarec,... % Error positivo
176176+ Lcurvarec - (Lerr(1)*Dist+Lerr(3)),... % Error negativo
177177+ 'Color',colores(iCL,:),'LineStyle','none')
178178+% Muestra la curva
179179+Curv(3)=plot(Distplot,Lplot,'Color',colores(iCL,:),'LineWidth',1.2);
180180+181181+% A�ade las rejillas de las graficas
182182+grid on
183183+grid minor
184184+185185+% % Obtener punto de cruce
186186+% CortesInd = find(abs(Dplot-Lplot)<=(0.01));
187187+% if ~isnan(CortesInd)
188188+% DistCorte = Distplot(CortesInd(1));
189189+% text(DistCorte,Dplot(CortesInd(1))+1,...
190190+% {'EASE',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorte),' m'])},...
191191+% 'VerticalAlignment','bottom','HorizontalAlignment','left')
192192+% end
193193+194194+195195+% Obtener numero de ceros decimales de las pendientes, sumarle 1 y convertir a
196196+% string, para mostrar tantos numeros decimales en las funciones que se ven en
197197+% la leyenda
198198+P11 = num2str(fix(abs(log10(abs(Dcoef.b))))+2);
199199+P21 = num2str(fix(abs(log10(abs(Ecoef.b))))+2);
200200+P31 = num2str(fix(abs(log10(abs(Lcoef.p1))))+2);
201201+202202+% Colores en formato texto para el color de las funciones
203203+ColD = [num2str(colores(iCD,1)),',',num2str(colores(iCD,2)),',',num2str(colores(iCD,3))];
204204+ColE = [num2str(colores(iCE,1)),',',num2str(colores(iCE,2)),',',num2str(colores(iCE,3))];
205205+ColL = [num2str(colores(iCL,1)),',',num2str(colores(iCL,2)),',',num2str(colores(iCL,3))];
206206+207207+% Leyendas
208208+leyenda{1} = sprintf(['\\bf0 %s %d ms\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.2f�x^{%4.',P11,'f} \n \\color{white}.'],'a',1,Dres.adjrsquare,ColD,Dcoef.a,Dcoef.b);
209209+leyenda{2} = sprintf(['\\bf%d ms %d ms\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.2f�x^{%4.',P21,'f} \n \\color{white}.'],1,Rango,Eres.adjrsquare,ColE,Ecoef.a,Ecoef.b);
210210+leyenda{3} = sprintf(['\\bf%d ms %s\\rm R^2_{adj} = %4.2f\n\\color[rgb]{%s}y = %4.',P31,'f�x+%4.2f \n \\color{white}.'],Rango,'a infinito',Lres.adjrsquare,ColL,Lcoef.p1,Lcoef.p2);
211211+212212+%% Teoria corregida
213213+% Si se ha marcado el calculo de la teoria revisada corregida se calcula y
214214+% se a�ade a la grafica
215215+if get(handles.teoriacorregida,'value')==1
216216+ %%% PARAMETROS
217217+ % Nivel total de la fuente a 1 metro
218218+ SPL = 10*log10(sum(10.^(handles.SPLm{handles.Index,13}/10)));
219219+ % Volumen (m3)
220220+ V = handles.SPLm{handles.Index,15};
221221+ % Superficie (m2)
222222+ S = handles.SPLm{handles.Index,16};
223223+ % Mean Free Path
224224+ mfp = 4*V/S;
225225+ % Absorcion media
226226+ alpha = mean(handles.SPLm{handles.Index,11});
227227+ % Absorci�n equivalente de Eyring
228228+ A = -S*log(1-alpha);
229229+ % Temperatura de la sala
230230+ temp = handles.SPLm{handles.Index,17};
231231+ % Velocidad del sonido
232232+ c = 331.4 + 0.6*temp;
233233+ % Densidad del aire. Presion Atm / (constante gas*Temp
234234+ % absoluta)
235235+ rho = 101325 / (287.058*(273.15+temp));
236236+ % Impedancia acustica del aire
237237+ Z = rho*c;
238238+ % Presion de referencia
239239+ pref = 2*10^(-5);
240240+ % Factor de conversion
241241+ Fac = Z/(pref^2);
242242+ % Directividad de la fuente
243243+ Q = str2double(get(handles.Qdir,'string'));
244244+ % Nivel de potencia de la fuente (SPL a 1 metro). Se supone que Q=1
245245+ SWL = SPL - 10*log10(1/(4*pi*1));
246246+ % Potencia de la fuente en vatios
247247+ W = 10.^(SWL/10)*10^-12;
248248+ % Tiempo de reverberacion de Eyring
249249+ T = 6*log(10)/c * mfp * 1/(-log(1-alpha));
250250+ % Rango de integracion temporal (s)
251251+ t = handles.Rango * 10^(-3);
252252+253253+ % Para no mostrar errores cuando se repite el calculo de coeficientes
254254+ warning ('off','all');
255255+256256+ %% Calculo de coeficiente para el campo directo
257257+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
258258+ try % Intenta el calculo con puntos de inicio random
259259+ opD = fitoptions('Method','NonlinearLeastSquares',...
260260+ 'Robust','LAR',...
261261+ 'Lower',[0,0],... % Minimo valor de los coeficientes
262262+ 'Upper',[20,20],... % Maximo valor de los coeficientes
263263+ 'MaxFunEvals',3000,...
264264+ 'MaxIter',3000,...
265265+ 'TolFun',10^-3);
266266+ fD = fittype('Fac * W*Q./(4*pi*dist.^2)*Cd',...
267267+ 'dependent',{'y'},...
268268+ 'independent',{'dist'},...
269269+ 'problem', {'Q','W','Fac'},...
270270+ 'coefficients',{'Cd'},...
271271+ 'options',opD);
272272+ [fitiD,gofD,outputD] = fit(Distplot',10.^(Dplot'/10),fD,'problem',{Q,W,Fac});
273273+ break;
274274+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
275275+ if ii==str2double(get(handles.numIntentos,'string'))
276276+ hold off
277277+ ed = errordlg('No se ha podido obtener coeficientes (Directo), intentalo de nuevo','Error');
278278+ set(ed, 'WindowStyle', 'modal');
279279+ uiwait(ed);
280280+ return;
281281+ end
282282+ end
283283+ end
284284+285285+286286+ %% Calculo de coeficientes epsilon y Cl para campo late
287287+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
288288+ try % Intenta el calculo con puntos de inicio random
289289+ fL = fittype('Fac * (4*W)/(S*(-log(1-alpha))) * exp(-(13.82*(dist/c+t)*el/T)) * Cl',...
290290+ 'dependent',{'y'},...
291291+ 'independent',{'dist'},...
292292+ 'problem', {'W','S','alpha','t','T','c','Fac'},...
293293+ 'coefficients',{'el','Cl'});
294294+ [fitiL,gofL,outputL] = fit(Distplot',10.^(Lplot'/10),fL,'problem',{W,S,alpha,t,T,c,Fac});
295295+ break;
296296+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
297297+ if ii==str2double(get(handles.numIntentos,'string'))
298298+ hold off
299299+ ed = errordlg('No se ha podido obtener coeficientes (Late), intentalo de nuevo','Error');
300300+ set(ed, 'WindowStyle', 'modal');
301301+ uiwait(ed);
302302+ return;
303303+ end
304304+ end
305305+ end
306306+307307+ %% Calculo de coeficientes epsilon y Ce para campo early
308308+ for ii = 1:str2double(get(handles.numIntentos,'string')) % 100 intentos de obtener los coeficientes
309309+ try % Intenta el calculo con puntos de inicio random
310310+ opE = fitoptions('Method','NonlinearLeastSquares',...
311311+ 'Robust','LAR',...
312312+ 'MaxFunEvals',3000,...
313313+ 'MaxIter',3000,...
314314+ 'TolFun',10^-3);
315315+ fE = fittype('Fac * ((4*W)./(S*(-log(1-alpha))*dist) .* (exp(-(13.82*(dist/c)*ee/T))*Ce - exp(-(13.82*(dist/c+t)*el/T)) * Cl))',...
316316+ 'dependent',{'y'},...
317317+ 'independent',{'dist'},...
318318+ 'problem', {'W','S','alpha','T','t','c','Fac','el','Cl'},...
319319+ 'coefficients',{'ee','Ce'},...
320320+ 'options',opE);
321321+ [fitiE,gofE,outputE] = fit(Distplot',10.^(Eplot'/10),fE,'problem',{W,S,alpha,T,t,c,Fac,fitiL.el,fitiL.Cl});
322322+ break;
323323+ catch % Si no se ha podido obtener unos coeficientes ejecuta lo siguiente
324324+ if ii==str2double(get(handles.numIntentos,'string'))
325325+ hold off
326326+ ed = errordlg('No se ha podido obtener coeficientes (Early), intentalo de nuevo','Error');
327327+ set(ed, 'WindowStyle', 'modal');
328328+ uiwait(ed);
329329+ return;
330330+ end
331331+ end
332332+ end
333333+ warning ('on','all');
334334+335335+ PDplot = 10*log10(Fac * ( W*Q./(4*pi*Distplot.^2)*fitiD.Cd));
336336+ Peplot = 10*log10(Fac *(...
337337+ (4*W)./(S*(-log(1-alpha))*(Distplot)) .* ...
338338+ (exp(-(13.82*(Distplot/c)*fitiE.ee/T))*fitiE.Ce - exp(-(13.82*(Distplot/c+t)*fitiL.el/T))*fitiL.Cl)));
339339+ Plateplot = 10*log10(Fac .* (4*W)./(S*(-log(1-alpha))) .* exp(-(13.82.*(Distplot./c+t).*fitiL.el/T)) .* fitiL.Cl);
340340+341341+ Curv(4) = plot(Distplot,PDplot,'-.','Color',colores(iCDt,:),'LineWidth',1);
342342+ Curv(5) = plot(Distplot,Peplot,'-.','Color',colores(iCEt,:),'LineWidth',1);
343343+ Curv(6) = plot(Distplot,Plateplot,'-.','Color',colores(iCLt,:),'LineWidth',1);
344344+345345+ % Colores en formato texto para el color de las funciones
346346+ ColDteo = [num2str(colores(iCDt,1)),',',num2str(colores(iCDt,2)),',',num2str(colores(iCDt,3))];
347347+ ColEteo = [num2str(colores(iCEt,1)),',',num2str(colores(iCEt,2)),',',num2str(colores(iCEt,3))];
348348+ ColLteo = [num2str(colores(iCLt,1)),',',num2str(colores(iCLt,2)),',',num2str(colores(iCLt,3))];
349349+350350+ % Leyendas
351351+ leyenda{4} = sprintf('\\bf0 ms %s %d ms\\rm Teoria revisada corregida\n \\color[rgb]{%s}C_D = %4.3f | R^2_{adj} = %4.2f \n \\color{white}.','a',1,ColDteo,fitiD.Cd,gofD.adjrsquare);
352352+ leyenda{5} = sprintf('\\bf%d ms %s %d ms\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_E = %4.3f | C_E = %4.3f | R^2_{adj} = %4.2f \n \\color{white}.',1,'a',Rango,ColEteo,fitiE.ee,fitiE.Ce,gofE.adjrsquare);
353353+ leyenda{6} = sprintf('\\bf%d ms %s\\rm Teoria revisada corregida\n \\color[rgb]{%s}\\epsilon_L = %4.3f | C_L = %4.3f | R^2_{adj} = %4.2f',Rango,'a infinito',ColLteo,fitiL.el,fitiL.Cl,gofL.adjrsquare);
354354+355355+356356+ % % Obtener punto de cruce
357357+ % f1a = 10*log10(Peplot);
358358+ % f2a = 10*log10(Plateplot);
359359+ % CortesInd = find(abs(f1a-f2a)<=(0.01));
360360+ % if ~isnan(CortesInd)
361361+ % DistCorteTeo = Distplot(CortesInd(1));
362362+ % text(DistCorteTeo,f1a(CortesInd(1))-1,...
363363+ % {'Te�rica',strcat('\bf\color{black}',[sprintf('%4.3f',DistCorteTeo),' m'])},...
364364+ % 'VerticalAlignment','bottom','HorizontalAlignment','right')
365365+ % end
366366+367367+ % Almacenar variables de interes para despues exportarlas dentro del
368368+ % .mat
369369+370370+ % Coeficientes
371371+ handles.Elate = fitiL.el;
372372+ handles.Clate = fitiL.Cl;
373373+ handles.Eearly = fitiE.ee;
374374+ handles.Cearly = fitiE.Ce;
375375+ handles.Cdirect = fitiD.Cd;
376376+377377+ % Parametros
378378+ handles.SPL = SPL; % Nivel de presion a 1 metro
379379+ handles.W = W; % Potencia
380380+ handles.Q = Q; % Directividad
381381+ handles.t = t; % Rango temporal en segundos
382382+ handles.T = T; % Tiempo de reverberaci�n de Eyring
383383+ handles.c = c; % Velocidad de sonido
384384+ handles.S = S; % Superficie
385385+ handles.V = V; % Volumen
386386+ handles.alpha = alpha; % Coeficiente de absorcion medio
387387+ handles.Z = Z; % Impedancia del aire
388388+ handles.rho = rho; % Densidad del aire
389389+ handles.A = A; % Absorcion equivalente de Eyring
390390+391391+ % Curvas
392392+ handles.Distancia = Distplot; % Vector de distancia
393393+ handles.EaseD = Dplot; % Curva del campo directo (EASE)
394394+ handles.EaseE = Eplot; % Curva del campo early (EASE)
395395+ handles.EaseL = Lplot; % Curva del campo late (EASE)
396396+ handles.TeoD = PDplot; % Curva del campo directo (Teorico)
397397+ handles.TeoE = Peplot; % Curva del campo early (Teorico)
398398+ handles.TeoL = Plateplot; % Curva del campo late (Teorico)
399399+400400+ % Actualizar variables en la aplicacion
401401+ guidata(hObject, handles);
402402+403403+end
404404+405405+lgdw=legend(Curv,leyenda);
406406+lgdw.FontSize = 11;
407407+lgdw.Location = 'bestoutside';
408408+%lgdw.Location = 'northeastoutside';
409409+% Si se utiliza Matlab 2014b o anterior no a�ade el titulo a la leyenda ya
410410+% que no es compatible
411411+if ~verLessThan('matlab','8.7')
412412+ title(lgdw,'Curvas')
413413+end
414414+ylabel('Nivel de presi�n ac�stica (dB)')
415415+xlabel('Distancia (m)')
416416+title({['SPL seg�n rango de tiempo',sprintf(' - %d ms',Rango)];...
417417+ ['\color{blue} ','Fuente: ',sprintf(': %s',Fuente(1))]});
418418+419419+hold off
420420+421421+