Давайте делиться рецептами и методами ввода входных параметров. Кому что нравится - менюшки, файлы с параметрами, подпрограммы именно для ввода и считывания, ну и так далее. Ясно, что дело вкуса, но, может, и что полезное удастся обнаружить на чужой кухне.
Входные параметры. Как оформляем
Сообщений 1 страница 26 из 26
Поделиться22007-06-15 17:56:52
Надь, у меня, ты знаешь, есть "глобальная" программа вводы параметров через файл с параметрами. НО она требует мучительных для меня объяснений с потенциальным пользователем. Ну, что давать или обойдемся?
Поделиться32007-06-15 18:10:37
Мне кажется, что в каком-то виде - да. Не уверена, что именно полный текст, но может, какие-то важные куски и приемы с объяснениями. Я именно с твоей собезьянничала в свое время и сделала подпрограммку для файла с параметрами в удобном для себя виде. Но идея была твоя. Я ее тоже приведу, только с компом разберусь, что-то он от жары дурит.
Поделиться42007-06-15 18:39:27
Ладно. В выходные попробую. Помниться, по первости, я и программку с интерфейсом сделала. Поищу.
Поделиться52007-06-17 11:38:12
Вот как оно у меня сделано. Сам файл с параметрами состоит из двух блоков: для уникальных переменных и для массивов. В верхнем для каждой переменной указывается тип переменной, имя, значение и комментарий. В нижней - для массивов эти параметры указываются в строках заголовка, а потом блоком считываются значения. Есть метка (!) позволяющая добавить дополнительный инлекс при считывании.
/// %f /// key_rw /// 0 /% key, if 0 nothing is read or written, if 1 - write no read, if 2 read and write
/// %s /// pth_crf /// D:\ont\cap_tail\shft\ /% Path for output file
/// %s /// fil_cc /// c_c_gr_wi_j4_p_pfp_prp.tsp /% Output file name
/// %s /// fil_rc /// r_c_gr_wi_j4_p_pfp_prp /% Output file name
/// %s /// extn_rc /// tsp /% Output file name extension
/// %f /// start_date /// 1997 01 01 /% Start date (Year, Month, Day)
/// %f /// fin_date /// 1998 12 31 /% Last date (Year, Month, Day)
/// %f /// len_crf /// 30 1 30 /% Correlation length
/// %f /// day_max /// 6 1 6 /% maximal number of days in one interval
/// %f /// tim_dsc /// 0 86400 /% Ut interval
/// %f /// hour_int /// 0 1 0 24 /% Ut interval in hours
/// %f /// tim_ac /// 0.04 /% time accuracy
/// %f /// col_m_int /// 2 13 /% columns to calculate mean values
/// %f /// col_crf /// 2 3 4 5 6 7 8 /% columns for correlation
/// %f /// col_x_num /// 2 2 2 /% number of columns to exclude
/// %f /// col_x /// 5 6 5 7 6 7 /% columns to exclude
/// %f /// col_yc /// 2 3 4 /% columns for correlations independent on x, constant
/// %f /// col_yv_num /// 1 1 1 /% number of columns to exclude
/// %f /// col_yv /// 7 6 5 /% columns for correlations independent on x, variable
/// %f /// col_yx /// 2 3 /% columns to calculate correlations on linear combination
/// %f /// col_b /// 9 10 11 /% columns of B
/// %f /// col_pfb /// 9 10 11 /% columns of dB
/// %f /// col_pr /// 7 /% columns for pressure
/// %f /// key_b /// 1 /% key for B
/// %f /// key_db /// 0 /% key for dB
/// %f /// key_sep /// 0 /% key for separation
/// %s /// pth_sep /// D:\ont\pi3_space\data\ /% Path for events file
/// %s /// fil_sep /// events_a.txt /% events file
/// %f /// val_sep /// 1 2 3 4 5 6 /% values of events
/// %f /// key_len_diur /// 1 /% key if >0 length of sample is written
#blk_start
||| %s ||| %s ||| %f ||| %f ||| %s ||| %f /% Format for reading
||| pth_in ||| fil_in ||| col ||| key_log ||| var_nam ||| ampl_lim /% Names of block variables
||| d:\ont\cap_tail\shft\ /% Path to input file
||| gr_pfb_60s_1997_1998_1.txi /% File name
||| 2 5 /% column numbers to read
||| 0 0 /% key for each column if >0 -> log, if 0 - linear
||| VOS /% Variable name
!!! THL /% Variable name
||| 16 0 111 0 /% Interval of valid values
!!! 16 0 111 0 /% Interval of valid values
||| d:\ont\cap_tail\shft\ /% Path to input file
||| wi_pfbz_1997_1998.tsh /% file name
||| 3 /% column numbers to read
||| 1 /% key for each column if >0 -> log, if 0 - linear
||| wi_pfbz /%
||| 1e6 1e-5 1e11 0 /% Interval of valid values
||| d:\ont\cap_tail\shft\ /% Path to input file
||| wi_pfp_1997_1998.tsh /% file name
||| 3 /% column numbers to read
||| 1 /% key for each column if >0 -> log, if 0 - linear
||| wi_pfp /%
||| 1e6 1e-5 1e11 0 /% Interval of valid values
||| d:\ont\cap_tail\shft\ /% Path to input file
||| wiam_1997_1998.txt /% file name
||| 5 /% column numbers to read
||| 1 /% key for each column if >0 -> log, if 0 - linear
||| wi_jp4 /%
||| 1e10 1e-9 1e11 0 /% Interval of valid values
||| d:\ont\cap_tail\shft\ /% Path to input file
||| wiap_1997_1998.tsh /% file name
||| 2 3 /% column numbers to read
||| 0 0 /% key for each column if >0 -> log, if 0 - linear
||| wi_p /%
!!! wi_vx /%
||| 1e5 1e-9 1e11 0 /% Interval of valid values
!!! 1e5 -2e5 1e11 0 /% Interval of valid values
||| d:\ont\cap_tail\shft\ /% Path to input file
||| wiab_1997_1998.tsh /% File name
||| 2 3 4 /% column numbers to read
||| 0 0 0 /% key for each column if >0 -> log, if 0 - linear
||| wi_Bx /% Altitude of the orbit
!!! wi_By /%
!!! wi_Bz /%
||| 200 -200 1e11 0 /% Interval of valid values
!!! 200 -200 1e11 0 /%
!!! 200 -200 1e11 0 /%
||| d:\ont\cap_tail\shft\ /% Path to input file
||| wiax_1997_1998.txm /%
||| 2 3 4 /% column numbers to read
||| 0 0 0 /% key for each column if >0 -> log, if 0 - linear
||| wi_x /% Altitude of the orbit
!!! wi_y /%
!!! wi_z /%
||| 3e5 50 6e5 0 /% Interval of valid values
!!! 3e5 -3e5 6e5 0 /%
!!! 3e5 -3e5 6e5 0 /%
#blk_end
#par_end
© n_y, 2006.11.23
Поделиться62007-06-17 11:41:43
Читается файл стандартной подпрограммой в 2 переменных - vrb и blk - для переменных и массивов (имеются в виду структурный массив, где есть строковые переменный или обычные массивы в качестве элементов)
function [vrb,blk]=rd_par(pth,fil)
% Reads parameter file according to description fields
% and puts the results into a cell arrays in which each element
% is an expression to evaluate, for example
% 'i_yr=98;'
% fil_nam{1}='tst.txt', etc
%clear all
%pth='d:\ont\satellites\';
%fil='sat_omni.par';
blk=[];
f_pr=sprintf('%s', pth, fil); % Full name for parameter file
i_par=fopen(f_pr)
key_blk=0;
if i_par>0 %1
k_str=0; % Counter of lines in the output cell array
k_vrb=0;
k_blk=0;
kt_blk=0;
% Reading variables
key_read=1;
while key_read==1 %2
s_lin=fgets(i_par);
l_l=length(s_lin);
if l_l>=8 & s_lin(1:8)=='#par_end'
key_read=0;
end
if l_l>=3 & s_lin(1:3)=='///' %3
k_str=k_str+1;
k_vrb=k_vrb+1;
str1=s_lin(4:l_l);
f_3=findstr(str1, '///');
no_slash=isempty(f_3);
if no_slash==0
str2=str1(1:f_3(1)-1);
frmt=sscanf(str2, '%s');
vr_0=str1(f_3(1)+3:f_3(2)-1);
vr=sscanf(vr_0, '%s')
str3=str1(f_3(2)+3:l_l-3);
num_s4=findstr(str3, '/%');
no_cmnt=isempty(num_s4);
if no_cmnt==0
str4=str3(1:num_s4(1)-1);
else
str4=str3;
end
vr_vl=sscanf(str4,frmt)
if frmt=='%f' | frmt =='%i' %4
vr_vl=vr_vl';
end %3
vrb{k_vrb,1}=frmt;
vrb{k_vrb,2}=vr;
vrb{k_vrb,3}=vr_vl;
end
end %2
if l_l>=10 & s_lin(1:10)=='#blk_start' %3
key_blk=1;
k_blk=0;
while key_blk==1 %4
s_lin=fgets(i_par)
l_l=length(s_lin);
if l_l>=8 & s_lin(1:8)=='#blk_end'
key_blk=0
end
if l_l>=3 %5
str_str=s_lin(1:3);
if str_str=='|||'
k_blk=k_blk+1;
k_in=1;
else
k_in=k_in+1;
end
f_cnt=findstr(s_lin, str_str);
f_end=findstr(s_lin, '/%');
f_str=[f_cnt,f_end];
l_f=length(f_str);
% pause
for i_bl=1:l_f-1 %6
f1=f_str(i_bl)+3;
f2=f_str(i_bl+1)-1;
str=s_lin(f1:f2);
if k_blk<=2; %7
str1=sscanf(str, '%s');
blk{i_bl,k_blk}=str1;
else
s_blk=size(blk);
w_blk=s_blk(1,1);
k_col=floor((k_blk-3)/w_blk)+1;
k_r=k_blk-2-w_blk*(k_col-1);
frmt=blk{k_r,1};
blk_vl=sscanf(str,frmt);
if frmt == '%f' | frmt=='%i' %9
blk_vl=blk_vl';
end %8
blk{k_r,3}{k_col,k_in}=blk_vl;
end %6
end %5
end %4
end %3
end
end
end
© n_y, 2003.08.24
Поделиться72007-06-17 16:53:45
А так выглядит обращение к этой подпрограмме из головной. По маске идет выход на директорию, из менюшки выбирается файл с параметрами, а asignin - это функция присвоения переменной значения выподняется отдельно для переменных и структурных массивов.
pth='d:\ont\cap_tail\par\';
%pth='d:\ont\mev_el\data\par\';
fil_mask='*.par';
mask_full=sprintf('%s', pth, fil_mask)
[fil_par, pathname] = uigetfile(mask_full, 'Input parameter file');
[vrb,blk]=rd_par_f(pth,fil_par);
s_v=size(vrb);
l_v=s_v(1,1); % length
% assignment of variables
for i_v=1:l_v
assignin('base', vrb{i_v,2},vrb{i_v,3}); % Asignment of variables
end
% assignment of cell arrays
s_b=size(blk);
l_b=s_b(1,1);
for i_b=1:l_b
s_in=size(blk{i_b,3});
w_in=s_in(1,2);
assignin('base', blk{i_b,2},blk{i_b,3});
end
© n_y, 2003.08.24
Поделиться82007-06-17 17:34:26
У меня так выглядит файл с параметрами
/*
1 - mat
2 - ASCII
3 - SuperFiles
4 - ASCII without comment file (without *.txt)
*/
Select type of file - tip_file = 2;
/*
1-th colomn is stations codes e.g. P03, ha0, A80;
2-th colomn is magnitometers codes - S - s.-coil mag, F - f.-gate mag, R - riometer;
3-th colomn is the total number of colomn in file.
4-th colomn is selected column (component);
5-th colomn is label.
6-th colomn is max level in the dymanic spectrum. If value = 0 without correct.
7-th colomn is min level in the dymanic spectrum. If value = -1 Level_min = mean in in the dymanic spectrum.
*/
START_SELECTED_STATIONS
mif B 5 2 B 0 0 D:\1999_many_Intervals\IKI\70321\ ;
mif B 5 4 B_Y 0 0 D:\1999_many_Intervals\IKI\70321\ ;
n1n flux 5 2 flux 0 0 D:\1999_many_Intervals\IKI\70321\ ;
END_SELECTED_STATIONS;
A80 S 4 2 -66\circ 0 0 D:\DATA\Bas_data\Coil_Mat\ ;
Comment on the top of the plot - Label_Fig = ~; /* if value = ~ - without comment */
Maximal Power (Y scale) for all stations - Max_Pover = 0; /* if value = 0 - without correct*/
The appendix to the name of output file - output_appendix = ~; /* if value = ~ - without appendix*/
Year - year = 1997;
Day # start(1..365) - day_start = 80;
START_SELECTED_TIME_INTERVALS
7 00 7 20;
7 10 7 30;
7 20 7 40;
7 30 7 50;
7 40 7 60;
7 50 8 10;
8 00 8 20;
8 10 8 30;
8 20 8 40;
8 30 8 50;%10
8 40 8 60;
8 50 9 10;
9 00 9 20;
9 10 9 30;
9 20 9 40;
9 30 9 50;
9 40 9 60;
9 50 10 10;%18
10 00 10 20;
10 10 10 30;
10 20 10 40;
10 30 10 50;
10 40 10 60;
10 50 11 10;
11 00 11 20;
11 10 11 30;
11 20 11 40;
11 30 11 50;
11 40 11 60;
11 50 12 10;
12 00 12 20;
12 10 12 30;
12 20 12 40;
12 30 12 50;
12 40 12 60;
12 50 13 10;
13 00 13 20;
13 10 13 30;
13 20 13 40;
13 30 13 50;
13 40 13 60;
13 50 14 10;
END_SELECTED_TIME_INTERVALS;
Directory with input data - pathname_in = D:\DATA\IKI_mif_file\ ;
Directory with comment txt - pathname_comm = D:\DATA\IKI_mif_file\ ;
Directory for output plots - pathname_out = D:\1999_many_Intervals\IKI\70321\Appox_BByFlux\ ;
Sampling frequency (Hz) - Fsl = 1;
Spectrum High freq. (Hz) - Fh = 0.495;
Spectrum Low freq. (Hz) - Fl = 0.001;
Number of X grid lines - Y_grid_all = 5;
Window (in samples) for spectral smoothing (Box method) - WSIZE = 1;
To pre-filter the data? - Filter = 0; /* 0 - NOT,
1 - Butterworth filter 4 order Bandpass,
2 - Butterworth filter 4 order Low pass
3 - filter by smoothing of data; 1/Fl_Filtr is size of window for smoothing of data
*/
High freq. filter(Hz) - Fh_Filtr = 0.495;
Low freq. filter(Hz) - Fl_Filtr = 0.0005;
To save Spectrum? - SaveFiltrSon = 0; /* 0 - NOT, 1 - YES */
To save ascii file? - SaveAscii = 0; /* 0 - NOT, 1 - YES */
Is the scale log? - ScaleAmp = 0; /* 0 - LINE, 1 - LOG*/
Is the frequency-scale log? - ScaleFqr = 0; /* 0 - LINE, 1 - LOG*/
printmode_for_magnitogram = -dtiff;/*-dbmpmono, -dpcxmono, deps */
landscape = 0; /* if 0 normaly 1 - album */
Method_despiked = 2; /* 1 - yours, 2 - my*/
Val_despik = 0; /* if Method - 1, the unit is the percent(%). If it is 0, there is no this process in the program */
/* if Method - 2, the level of standard deviation */
/*Estimates the Power Spectral Density using:
Welch's averaged, modified periodogram method -PSD
via Burg's method -PBURG
via the Thomson multitaper method -PMTM
estimate via Yule-Walker's method -PYUL*/
Estimat_Method = PYUL;
Parameter for PYUL( the unit is the percent(%) from N_FFT ) - order_PYUL = 3;
It is the integer specifying the order of an autoregressive (AR)
prediction model for the signal, used in estimating the PSD.
START_ADDED_FILES
2 mif B 5 4 B_Y ~ D:\1999_many_Intervals\IKI\70321\ ;
2 mif B 5 5 B_Z ~ D:\1999_many_Intervals\IKI\70321\ ;
13 sin S 15 4 \thetaB_n ~ D:\1999_many_Intervals\IKI\70321\ ;
END_ADDED_FILES;
10 wind S 12 13 \thetaWIND ~ D:\IMF\Correct_data\1997_mag\ ;
Поделиться92007-06-17 17:36:09
Программа для чтения параметров.
%--------------------------------------
function [Net, Struct_NS, Struct_Time, Add_Files] = read_param( name_par, Net )
%Read file with parametry. It is ago.par
ParName = { 1, 100 };
fid = fopen( name_par, 'r' );
if (fid == -1) str = sprintf('not found - %s', name_in);disp(str);return; end;
ParName{1,1} = ' Fsl ';
ParName{1,2} = ' order_PYUL ';
ParName{1,3} = ' Label_Fig ';
ParName{1,4} = ' day_start ';
ParName{1,5} = ' hour_start ';
ParName{1,6} = ' Max_Pover ';
ParName{1,7} = ' year ';
ParName{1,8} = ' hour_end ';
ParName{1,9} = ' minute_end ';
ParName{1,10} = ' START_SELECTED_STATIONS';
ParName{1,11} = ' minute_start ';
ParName{1,12} = ' output_appendix ';
ParName{1,13} = ' ScaleAmp ';
ParName{1,14} = ' manner_plot ';
ParName{1,15} = ' Filter ';
ParName{1,16} = ' Fh_Filtr ';
ParName{1,17} = ' Fl_Filtr ';
ParName{1,18} = ' AmpSpecKoef ';
ParName{1,19} = ' Fh ';
ParName{1,20} = ' Fl ';
ParName{1,21} = ' SaveAscii ';
ParName{1,22} = ' lag ';%free
ParName{1,23} = ' Control_Nfft ';%free
ParName{1,24} = ' pathname_out ';
ParName{1,25} = ' SaveFiltrSon ';
ParName{1,26} = ' SaveSimpSon ';%free
ParName{1,27} = ' DrawFiltrSon ';%free
ParName{1,28} = ' DrawSimpSon ';%free
ParName{1,29} = ' DrawDynamicSpectra ';%free
ParName{1,30} = ' day_end ';
ParName{1,31} = ' pathname_in ';
ParName{1,32} = ' colormap ';%free
ParName{1,33} = ' printmode_for_dynamic ';%free
ParName{1,34} = ' Val_despik ';
ParName{1,35} = ' Method_despiked ';
ParName{1,36} = ' ScaleFqr ';
ParName{1,37} = ' number_column ';
ParName{1,38} = ' parameter_IMF ';%free
ParName{1,39} = ' show_IMF ';%free
ParName{1,40} = ' WSIZE ';
ParName{1,41} = ' START_ADDED_FILES';
ParName{1,42} = ' Estimat_Method ';
ParName{1,43} = ' name_IMF '; %free
ParName{1,44} = ' landscape ';
ParName{1,45} = ' Y_grid_all ';
ParName{1,46} = ' printmode_for_magnitogram ';%free
ParName{1,47} = ' tip_file ';
ParName{1,48} = ' pathname_comm ';
ParName{1,49} = ' number_error ';
ParName{1,50} = ' Font_size ';
ParName{1,51} = ' Time_step ';
ParName{1,52} = ' H_number_error ';
ParName{1,53} = ' D_number_error ';
ParName{1,54} = ' Z_number_error ';
ParName{1,55} = ' START_SELECTED_TIME_INTERVALS';
n = size(ParName, 2);
while 1
line = fgetl(fid);
[i,j] = size(line);
if ~isstr(line); break; end;
if( j < 4 ) continue;end;
for( k = 1 : n)
k_sta = findstr( line, char(ParName(k)));
if( ~isempty( k_sta ) )
if( k == 1 ) Net.Fsl = GetPar( line );break;end;
if( k == 2 ) Net.order_PYUL = GetPar( line );break;end;
if( k == 3 ) Net.Label_Fig = GetStr( line );break;end;
if( k == 4 ) Net.day_start = GetPar( line );break;end;
if( k == 5 ) Net.hour_start = GetPar( line );break;end;
if( k == 6 ) Net.Max_Pover = GetPar( line );break;end;
if( k == 7 ) Net.year = GetPar( line );break;end;
if( k == 8 ) Net.hour_end = GetPar( line );break;end;
if( k == 9 ) Net.minute_end = GetPar( line );break;end;
if( k == 10 ) [Struct_NS, Net.numbers_stations] = Input_Inf_Station(fid);break;end;
if( k == 11 ) Net.minute_start = GetPar( line );break;end;
if( k == 12 ) Net.output_appendix = GetStr( line );break;end;
if( k == 13 ) Net.ScaleAmp = GetPar( line );break;end;
if( k == 14 ) Net.manner_plot = GetPar( line );break;end;
if( k == 15 ) Net.Filter = GetPar( line );break;end;
if( k == 16 ) Net.Fh_Filtr = GetPar( line );break;end;
if( k == 17 ) Net.Fl_Filtr = GetPar( line );break;end;
if( k == 18 ) Net.AmpSpecKoef = GetPar( line );break;end;
if( k == 19 ) Net.Fh = GetPar( line );break;end;
if( k == 20 ) Net.Fl = GetPar( line );break;end;
if( k == 21 ) Net.SaveAscii = GetPar( line );break;end;
% if( k == 22 ) Net.lag = GetPar( line );break;end;
% if( k == 23 ) Net.Control_Nfft = GetStr( line );break;end;
if( k == 24 ) Net.pathname_out = GetStr( line );break;end;
if( k == 25 ) Net.SaveFiltrSon = GetPar( line );break;end;
% if( k == 26 ) Net.SaveSimpSon = GetPar( line );break;end;
% if( k == 27 ) Net.DrawFiltrSon = GetPar( line );break;end;
% if( k == 28 ) Net.DrawSimpSon = GetPar( line );break;end;
% if( k == 29 ) Net.DrawDynamicSpectra = GetPar( line );break;end;
if( k == 30 ) Net.day_end = GetPar( line );break;end;
if( k == 31 ) Net.pathname_in = GetStr( line );break;end;
% if( k == 32 ) Net.colormap = GetStr( line );break;end;
% if( k == 33 ) Net.printmode_for_dynamic = GetStr( line );break;end;
if( k == 34 ) Net.Val_despik = GetPar( line );break;end;
if( k == 35 ) Net.Method_despiked = GetPar( line );break;end;
if( k == 36 ) Net.ScaleFqr = GetPar( line );break;end;
if( k == 37 ) Net.number_column = GetPar( line );break;end;
% if( k == 38 ) Net.parameter_IMF = GetPar( line );break;end;
% if( k == 39 ) Net.show_IMF = GetPar( line );break;end;
if( k == 40 ) Net.WSIZE = GetPar( line );break;end;
if( k == 41 ) [Add_Files, Net.numbers_add_files] = Input_Inf_Add_Files(fid);break;end;
if( k == 42 ) Net.Estimat_Method = GetStr( line );break;end;
% if( k == 43 ) Net.name_IMF = GetStr( line );break;end;
if( k == 44 ) Net.landscape = GetPar( line );break;end;
if( k == 45 ) Net.Y_grid_all = GetPar( line );break;end;
if( k == 46 ) Net.printmode_for_magnitogram = GetStr( line );break;end;
if( k == 47 ) Net.tip_file = GetPar( line );break;end;
if( k == 48 ) Net.pathname_comm = GetStr( line );break;end;
if( k == 49 ) Net.number_error = GetPar( line );Net = Read_Bad_Intervals( Net, fid );break;end;
if( k == 50 ) Net.Font_size = GetPar( line );break;end;
if( k == 51 ) Net.Time_step = GetPar( line );break;end;
if( k == 52 ) Net.H_number_error = GetPar( line ); Net = Read_Bad_Intervals_HDZ( Net, fid, Net.H_number_error, 1 );break;end;
if( k == 53 ) Net.D_number_error = GetPar( line ); Net = Read_Bad_Intervals_HDZ( Net, fid, Net.D_number_error, 2 );break;end;
if( k == 54 ) Net.Z_number_error = GetPar( line ); Net = Read_Bad_Intervals_HDZ( Net, fid, Net.Z_number_error, 3 );break;end;
if( k == 55 ) [Struct_Time, Net.number_intervals] = Input_Inf_Intervals(fid);break;end;
end;
end;
end
fclose(fid);
%--------------------------------------
%--------------------------------------
function [NS, t] = Input_Inf_Add_Files(fid)
NS = struct( 'type_file_str', {'test'}, ...
'name_stations', {'test'}, ...
'tip', {'test'}, ...
'num', {'test'}, ...
'label', {'test'}, ...
'total_number_str', {'test'}, ...
'pos_sattel', 0, ...
'dir', {'test'} );
line = fgetl(fid);
if ~isstr(line); disp('Error 1 in Input_Additional_Flies ');return; end;
if ( isempty(findstr(line, 'END_ADDED_FILES')) ~= 1 ); t = 0; return;end;
t = 1;
str = [];
while( isempty(str) == 1 )
[NS(t).type_file_str,rem] = strtok(line);
[NS(t).name_stations,rem] = strtok(rem);
[NS(t).tip,rem] = strtok(rem);
[NS(t).total_number_str,rem] = strtok(rem);
[NS(t).num,rem] = strtok(rem);
[NS(t).label,rem] = strtok(rem);
[NS(t).pos_sattel,rem] = strtok(rem);
[NS(t).dir,rem] = strtok(rem);
NS(t).type_file = sscanf(NS(t).type_file_str, '%d');
NS(t).total_number = sscanf(NS(t).total_number_str, '%d');
NS(t).colomn = sscanf(NS(t).num, '%d');
t = t + 1;
line = fgetl(fid);
if ~isstr(line); disp('Error 2 in Input_Names_Flies ');return; end;
str = findstr(line, 'END_ADDED_FILES');
end;
t = t - 1;
%--------------------------------------
%--------------------------------------
function Net = Read_Bad_Intervals_HDZ( Net, fid, num_err, j )
if( num_err == 0 ) return; end;
for( i = 1 : num_err )
line = fgetl(fid);
if ~isstr(line); break; end;
k = (i - 1)*2;
A = sscanf(line,'%d %d');
Net.Bad_Val_HDZ{j}(k+1) = A(1,1);
Net.Bad_Val_HDZ{j}(k+2) = A(2,1);
end;
%--------------------------------------
%--------------------------------------
function Net = Read_Bad_Intervals( Net, fid )
if( Net.number_error == 0 ) return; end;
for( i = 1 : Net.number_error )
line = fgetl(fid);
if ~isstr(line); break; end;
k = (i - 1)*2;
A = sscanf(line,'%d %d');
Net.Bad_Val(k+1) = A(1,1);
Net.Bad_Val(k+2) = A(2,1);
end;
%--------------------------------------
%--------------------------------------
function A = GetPar( str )
k_end = findstr(str, ';');
k_sta = findstr(str, '=');
if( str(k_end-1) == '%') k_end = k_end - 1;end;
str1 = str( k_sta+1 : k_end-1);
A = str2num(str1);
%--------------------------------------
%--------------------------------------
function A = GetStrNum( str )
k_end = findstr(str, ';');
k_sta = findstr(str, '=');
if(str(k_end-1) == '%') k_end = k_end - 1;end;
S = str( k_sta+1 : k_end-1);
A = sscanf(S,'%f');
%--------------------------------------
%--------------------------------------
function [Struct_NS, t] = Input_Inf_Station(fid)
Struct_NS = struct( 'name_stations', {'test'}, ...
'tip', {'test'}, ...
'num', {'test'}, ...
'label', {'test'}, ...
'max_str', {'test'}, ...
'min_str', {'test'}, ...
'total_number_str', {'test'}, ...
'colomn', 0, ...
'total_number', 0,...
'max', 0, ...
'min', 0, ...
'dir', {'test'});
line = fgetl(fid);
if ~isstr(line); disp('Error 1 in Input_Names_Flies ');return; end;
t = 1;
str = [];
while( isempty(str) == 1 )
[Struct_NS(t).name_stations,rem] = strtok(line);
[Struct_NS(t).tip,rem] = strtok(rem);
[Struct_NS(t).total_number_str,rem] = strtok(rem);
[Struct_NS(t).num,rem] = strtok(rem);
[Struct_NS(t).label,rem] = strtok(rem);
[Struct_NS(t).max_str,rem] = strtok(rem);
[Struct_NS(t).min_str,rem] = strtok(rem);
[Struct_NS(t).dir,rem] = strtok(rem);
Struct_NS(t).colomn = sscanf(Struct_NS(t).num, '%d');
Struct_NS(t).total_number = sscanf(Struct_NS(t).total_number_str, '%d');
Struct_NS(t).max = sscanf(Struct_NS(t).max_str, '%f');
Struct_NS(t).min = sscanf(Struct_NS(t).min_str, '%f');
t = t + 1;
line = fgetl(fid);
if ~isstr(line); disp('Error 2 in Input_Names_Flies ');return; end;
str = findstr(line, 'END_SELECTED_STATIONS');
end;
t = t - 1;
%--------------------------------------
%--------------------------------------
function A = GetStr( str )
k_end = findstr(str, ';');
k_sta = findstr(str, '=');
if(str(k_end-1) == '%') k_end = k_end - 1;end;
while( str( k_sta+1) == ' ') k_sta = k_sta + 1;end;
A = str( k_sta+1 : k_end-1);
%--------------------------------------
%--------------------------------------
function [Struct_Time, t] = Input_Inf_Intervals(fid)
Struct_Time = struct( 'hour_start', 0, ...
'minute_start', 0, ...
'hour_end', 0, ...
'minute_end', 0 );
line = fgetl(fid);
if ~isstr(line); disp('Error 1 in Input_Names_Flies ');return; end;
t = 1;
str = [];
while( isempty(str) == 1 )
[Struct_Time(t).h1,rem] = strtok(line);
[Struct_Time(t).m1,rem] = strtok(rem);
[Struct_Time(t).h2,rem] = strtok(rem);
[Struct_Time(t).m2,rem] = strtok(rem);
Struct_Time(t).hour_start = sscanf(Struct_Time(t).h1, '%f');
Struct_Time(t).minute_start = sscanf(Struct_Time(t).m1, '%f');
Struct_Time(t).hour_end = sscanf(Struct_Time(t).h2, '%f');
Struct_Time(t).minute_end = sscanf(Struct_Time(t).m2, '%f');
t = t + 1;
line = fgetl(fid);
if ~isstr(line); disp('Error 2 in Input_TIME_INTERVALS ');return; end;
str = findstr(line, 'END_SELECTED_TIME_INTERVALS');
end;
t = t - 1;
%--------------------------------------
Поделиться102007-06-17 17:37:31
То есть, у тебя он специализированный для данных? А я пошла по другому пути, и могу запихнуть в файл с параметрами вообще что угодно. А читалка все равно одна и та же. Мне кажется, что удобно.
Поделиться112007-06-17 17:37:52
И обращение к ней из главной программы.
[Net, Struct_NS, Struct_Time, Add_Files] = read_param( imfile, Net );
Поделиться122007-06-17 17:39:59
Нет. Это не специализированный ввод. Просто некоторые переменные объединены с структуру для большей компактности. Не передавать же 100 параметров по одному.
Поделиться132007-06-17 17:47:25
Пока не совсем поняла. У тебя присвоение имен идет в подпрограмме считывания? То есть, если имена будут другие, то подпрограмма тоже нужна новая?
Поделиться142007-06-17 17:59:00
Нет. Для новой переменной создается новое имя в структуре.
Поделиться152007-06-17 18:01:19
А подпрограмма не нужна новая. Программ для чтение 3-4. Чтение строковых переменных, чтение цифр и чтение структур 2-3 видов.
Поделиться162007-06-17 18:03:45
Конечно. Я просто для себя уточняла. Я тоже не всегда своей универсальной пользуюсь, это зависит от того, насколько программа часто используется. Если одноразовая, что-то быстро посмотреть, то прямо тексте все задаю, а, если более или менее надолго делаю, то в отдельном файле.
А вот, если речь, о программе не для себя, то лучше, чтобы в тексте вобще ничего можно было бы не менять. Надежнее получается.
Поделиться172007-06-17 18:05:55
Не, Оль, я опять запуталась.
Вот это из подпрограммы?
ParName{1,1} = ' Fsl ';
ParName{1,2} = ' order_PYUL ';
ParName{1,3} = ' Label_Fig ';
ParName{1,4} = ' day_start ';
ParName{1,5} = ' hour_start ';
ParName{1,6} = ' Max_Pover ';
Значит, если нужны будут другие имена, то надо в нее лезть или как?
Поделиться182007-06-17 18:24:34
Это не имена в программе - это метки в файле с параметрами. По ним ищется какой переменной присвоить значение.
Поделиться192007-06-17 18:34:55
Совсем я запуталась . Попробуй объяснить еще, может, пойму, пока никак.
Поделиться202007-06-17 18:41:17
Надь, ты вот как попробуй сделать. Скопируй всю эту муть. Но в файле с параметрами оставь только один параметр. Например - год. Убери из программы чтения все, что, по-твоему, не относиться к вводу этого года. Тогда программа будет минимальной и ты все сразу поймешь. Если не будет работать - клади все сюда и вместе разберемся.
Поделиться212007-06-17 18:43:27
Попробую, но не прямо сейчас. К ночи напишу, что получилось.
Поделиться222007-06-17 18:48:42
Да что там писать - знай себе стирай! А если что сотрешь лишнее - не беда, вставим!
Поделиться232007-06-17 20:10:53
Надь, В.А. просил меня накатать маленькую тестовую программку. Вот начала ее делать. Вот от нее читалка. Здесь совсем мало параметров. Наверно, будет понятней.
Файл с параметрами.
Half interval size - L = 3; /* interval will be from -3 to 3 */
Points number on this interval - number_points = 8;
- delta = 0.5;
Directory for input - pathname_out = D:\Footstep_IMF\;
Directory for output plots - pathname_in = D:\Footstep_IMF\;
Основная программа.
function Model_B_satellite( imfile )
global Net;
[name, pathname] = uigetfile('*.par', 'Input param file');
imfile = strcat( pathname, name );
Net = struct( 'pathname_out', {'test'}, ...
'pathname_in', {'test'},...
'delta', -1, 'L', 0, 'number_points', -1 );
disp(Net);
[Net] = read_param( imfile, Net );
disp(Net);
disp('Reading file with parameters has been finished');
Читалка.
%--------------------------------------
function [Net ] = read_param( name_par, Net )
%Read file with parametry. It is ago.par
ParName = { 1, 100 };
fid = fopen( name_par, 'r' );
if (fid ~= -1)
ParName{1,1} = ' L ';
ParName{1,2} = ' number_points ';
ParName{1,3} = ' pathname_out ';
ParName{1,4} = ' pathname_in ';
ParName{1,5} = ' delta ';
n = size(ParName, 2);
t = 1;
while 1
line = fgetl(fid);
[i,j] = size(line);
if ~isstr(line); break; end;
if( j < 4 ) continue;end;
for( k = 1 : n)
k_sta = findstr( line, char(ParName(k)));
if( ~isempty( k_sta ) )
if( k == 1 ) Net.L = GetPar( line );break;end;
if( k == 2 ) Net.number_points = GetPar( line );break;end;
if( k == 3 ) Net.pathname_out = GetStr( line );break;end;
if( k == 4 ) Net.pathname_in = GetStr( line );break;end;
if( k == 5 ) Net.delta = GetPar( line );break;end;
end;
end;
end
fclose(fid);
end;
%--------------------------------------
%--------------------------------------
function A = GetPar( str )
k_end = findstr(str, ';');
k_sta = findstr(str, '=');
if( strcmp(str(k_end-1),'%') == 1 ) k_end = k_end - 1;end;
str1 = str( k_sta+1 : k_end-1);
A = str2num(str1);
%--------------------------------------
%--------------------------------------
function A = GetStr( str )
k_end = findstr(str, ';');
k_sta = findstr(str, '=');
if(str(k_end-1) == '%') k_end = k_end - 1;end;
while( str( k_sta+1) == ' ') k_sta = k_sta + 1;end;
A = str( k_sta+1 : k_end-1);
%--------------------------------------
Поделиться242007-10-17 22:09:02
А если есть файл без описания с расширением mat, но я знаю примерно, что там массив типа omni. Как бы мне его считать внутри программы и переконвертировать в ascii?
Поделиться252007-10-18 00:52:22
Наташ, не поняла ничего. Совсем никакого описания? Вообще мат-файл считывается как структура и, если у нее значимые имена, то это может заменить описание. но это мои домыслы. Как там он на самом деле устроен - ???
Поделиться262007-10-18 11:30:28
Наташ, привет!
Если ты не знаешь, какие имена у структуры мат-файла, в рабочем окне напиши:
temp = whos( '-file', имя файла)
Если файл не в рабочей дирректории матлаба, то имя файла с путем к нему. После этого тебе напечатается список переменных структуры, из которой состоит файл. А дальше загрузишь ту переменную(переменные), какая нужна, с помощью load.