Codigos mathlab DIA PRACTICA IV
Wed Apr 03 2024 17:09:31 GMT+0000 (Coordinated Universal Time)
Saved by @Dasaju
%------------------------------------ %-Codigos para lab TPO %-captura function [senyal] = Captura(Fs) s = audiorecorder(Fs, 16, 1); record (s); pause (5); r=getaudiodata(s, 'int16'); % Converteixo a Double senyal = double(r); end %-------------------------------- %Radar doppler close all % Frequencia de mostreig Fs=22050; % Funció que captura el senyal del radar % NOMÉS APARTATS 2a i 3 % x=Captura(Fs); % APARTAT 2 (Comentar apartat 3) % % Transformada de Fourier % N=length(x); % % % % Nombre de punts, per zero padding augmentar N % % % AFEGUIU ELS ZEROS OPORTUNS DEPENEN DE LA RESOLUCIÓ FREQÜENCIAL % % % COMENTEU FUNCIÓ CAPTURA % % N= % % % % Representació de l'espectre % f=Fs*(-N/2:N/2-1)/N; % % w1 = window(@rectwin,length(x)); % x1=x.*w1; % X1=1/length(x)*fftshift(fft(x1,N)); % figure; % plot(f,abs(X1)); % grid on % xlabel('f[Hz]'); ylabel('abs(X)'); % % NOMES APARTAT 2c % % Enfinestrat triangular % w2 = window(@triang,length(x)); % x1=x.*w2; % X1=1/length(x)*fftshift(fft(x1,N)); % hold on % plot(f,abs(X1),'r'); % legend('Rectangular','Triangular') % % NOMES APARTAT 2d % % COMENTAR APARTATs 2a, 2b, 2c i 3 % % Enfinestrat Hamming % w3 = window(@hamming,length(x)); % x1=x.*w3; % X1=1/length(x)*fftshift(fft(x1,N)); % plot(f,abs(X1),'g'); % legend('Rectangular','Triangular','Hamming') % % APARTAT 3 (Comentar apartat 2) % % DESCOMENTAR FUNCIÓ CAPTURA % Transformada chirp fs = Fs; f1 = 100; f2 = 600; % en hertz m = 1024; w = exp(-j*2*pi*(f2-f1)/(m*fs)); a = exp(j*2*pi*f1/fs); figure; Z = czt(x,m,w,a); fz = ((0:length(Z)-1)'*(f2-f1)/length(Z)) + f1; plot(fz,1/length(x)*abs(Z)); xlabel('f(Hz)'); ylabel('Z') title('CZT') %------------------------------- %_--------------------------- %-Practica %Frequencia de mostreig Fs=22050*2; %Nombre de mostres N=44100; %Captura senyal audio s = wavrecord(N, Fs, 'int16'); %Converteixo a Double x=double(s); %Transformada de Fourier N=length(x); %Nombre de punts, per zero padding augmentar N X=fftshift(fft(x,N)); f=Fs*(-N/2:N/2-1)/N; figure; plot(f,abs(X)); xlabel('f(Hz)'); ylabel('X'); %Enfinestrat w1 = window(@rectwin,length(x)); w2 = window(@hamming,length(x)); x1=x.*w1; x2=x.*w2; X1=fftshift(fft(x1,N)); X2=fftshift(fft(x2,N)); figure; plot(f,abs(X1),f,abs(X2)); xlabel('f(Hz)'); ylabel('X');legend('Rectangular','Hamming'); %Transformada chirp fs = Fs; f1 = 100; f2 = 600; % en hertz m = 1024; w = exp(-j*2*pi*(f2-f1)/(m*fs)); a = exp(j*2*pi*f1/fs); figure; Z = czt(x,m,w,a); fz = ((0:length(Z)-1)'*(f2-f1)/length(Z)) + f1; plot(fz,abs(Z)); xlabel('f(Hz)'); ylabel('Z') title('CZT') %----------------------------------------- %-Prueba Fs=22050*2; x=double(DATA); X=fftshift(abs(fft(x))); figure(1) N=length(X); f=Fs*(-N/2:N/2-1)/N;h=plot(f,X) fs = Fs; f1 = 400; f2 = 600; % in hertz m = 1024; w = exp(-j*2*pi*(f2-f1)/(m*fs)); a = exp(j*2*pi*f1/fs); figure(2) z = czt(x,m,w,a); fz = ((0:length(z)-1)'*(f2-f1)/length(z)) + f1; plot(fz,abs(z)); %axis([f1 f2 0 1.2]) title('CZT') %-------------------------------------------------------------------------- %-Radar doppler function varargout = radardoppler(varargin) % RADARDOPPLER M-file for radardoppler.fig % RADARDOPPLER, by itself, creates a new RADARDOPPLER or raises the existing % singleton*. % % H = RADARDOPPLER returns the handle to a new RADARDOPPLER or the handle to % the existing singleton*. % % RADARDOPPLER('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in RADARDOPPLER.M with the given input arguments. % % RADARDOPPLER('Property','Value',...) creates a new RADARDOPPLER or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before radardoppler_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to radardoppler_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Copyright 2002-2003 The MathWorks, Inc. % Edit the above text to modify the response to help radardoppler % Last Modified by GUIDE v2.5 06-Oct-2008 21:14:40 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @radardoppler_OpeningFcn, ... 'gui_OutputFcn', @radardoppler_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before radardoppler is made visible. function radardoppler_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to radardoppler (see VARARGIN) % Choose default command line output for radardoppler handles.output = hObject; % %Poso fons blanc i amago boto % set(hObject,'color','w'); set(handles.hboto,'visible','off'); % Update handles structure guidata(hObject, handles); % UIWAIT makes radardoppler wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = radardoppler_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % -------------------------------------------------------------------- function LoadCaptura_Callback(hObject, eventdata, handles) % hObject handle to Load (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global CaptureData [filename, pathname] = uigetfile('*.vel', 'Pick an vel-file'); if isequal(filename,0) | isequal(pathname,0) disp('User pressed cancel') else file=fullfile(pathname, filename); load(file,'-mat'); end % -------------------------------------------------------------------- function Exit_Callback(hObject, eventdata, handles) % hObject handle to Exit (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) ButtonName=questdlg('Que vol fer?', ... 'Sortir del programa', ... 'Sortir','Cancelar','Cancelar'); switch ButtonName, case 'Sortir', close(gcf); end % -------------------------------------------------------------------- function Parametres_Callback(hObject, eventdata, handles) % hObject handle to Parametres (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global SamplingParameters S.Sampling_Rate = {'8000|11025|22050|{44100}', 'Sampling Rate(Hz)'}; S.Samples_Number={[10240] 'Number of Samples' [1 100000]}; S.Oscillator_Frequency={[24] 'Oscillator Frequency (GHz)' }; S.FFT_Points={[1024] 'Number of FFT points' [1 100000]}; S.Window_Type={ {'{rectwin}','bartlett' 'blackman' 'hamming'} }; S.Frequency_Unit={ {'{Hz}','m/s' 'km/h' 'mph'} }; SamplingParameters=StructDlg(S,'Sampling Parameters') if ~isempty(SamplingParameters), set(handles.hboto,'visible','on','string','Sample'); end; % -------------------------------------------------------------------- function TransformadaChirp_Callback(hObject, eventdata, handles) % hObject handle to TransformadaChirp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global SamplingData S.Oscillator_Frequency={[24] 'Oscillator Frequency (GHz)' }; S.Chirp_Points={[1024] 'Number of Chirp points' [1 100000]}; S.Window_Type={ {'{rectwin}','bartlett' 'blackman' 'hamming'} }; S.Start_Frequency={ [100] '' [0 44100]}; S.Stop_Frequency={ [700] '' [0 44100]}; S.Frequency_Unit={ {'{Hz}','m/s' 'km/h' 'mph'} }; SamplingParameters=StructDlg(S,'Sampling Parameters'); if ~isempty(SamplingParameters), Fs=SamplingData.Sampling_Rate; SamplingParameters.Samples_Number=length(SamplingData.Data); switch SamplingParameters.Window_Type, case 'rectwin', win=window(@rectwin,SamplingParameters.Samples_Number); case 'bartlett', win=window(@bartlett,SamplingParameters.Samples_Number); case 'blackman', win=window(@blackman,SamplingParameters.Samples_Number); case 'hamming', win=window(@hamming,SamplingParameters.Samples_Number); end m = SamplingParameters.Chirp_Points; f1=SamplingParameters.Start_Frequency; f2=SamplingParameters.Stop_Frequency; w = exp(-j*2*pi*(f2-f1)/(m*Fs)); a = exp(j*2*pi*f1/Fs); Z = czt(SamplingData.Data.*win,m,w,a); fz = ((0:length(Z)-1)'*(f2-f1)/length(Z)) + f1; figure; subplot(211); t=linspace(0,(SamplingParameters.Samples_Number-1)/Fs,SamplingParameters.Samples_Number)*1e3; %temps en ms plot(t,SamplingData.Data); xlabel('t(ms)'); ylabel('x(t)'); subplot(212); switch SamplingParameters.Frequency_Unit, case 'Hz', escala=1; TextUnit='Hz'; case 'm/s', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8/f0)/2; TextUnit='m/s'; case 'km/h', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/f0)/2; TextUnit='km/s'; case 'mph', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/1.6/f0)/2; TextUnit='mph'; end plot(fz*escala,abs(Z)); xlabel(TextUnit); ylabel('mag'); [m,I]=max(abs(Z)); title(['Maxim ',num2str(fz(I)*escala),' ',TextUnit]); end % -------------------------------------------------------------------- function PlotVelocitat_Callback(hObject, eventdata, handles) % hObject handle to ParametresVelocimetre (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global CaptureData S.Oscillator_Frequency={[24] 'Oscillator Frequency (GHz)' }; S.Frequency_Unit={ {'{Hz}','m/s' 'km/h' 'mph'} }; SamplingParameters=StructDlg(S,'Sampling Parameters'); if ~isempty(SamplingParameters), switch SamplingParameters.Frequency_Unit, case 'Hz', escala=1; TextUnit='Hz'; case 'm/s', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8/f0)/2; TextUnit='m/s'; case 'km/h', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/f0)/2; TextUnit='km/h'; case 'mph', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/1.609344/f0)/2; TextUnit='mph'; end figure; plot(1:length(CaptureData.FrequencyDoppler),CaptureData.FrequencyDoppler*escala); xlabel('Sample');ylabel(TextUnit); end; % -------------------------------------------------------------------- function CapturaVelocimetre_Callback(hObject, eventdata, handles) % hObject handle to CapturaVelocimetre (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global CaptureData SamplingData S.Sampling_Rate = {'8000|11025|22050|{44100}', 'Sampling Rate(Hz)'}; S.Samples_Number={[10240] 'Number of Samples' [1 100000]}; S.Oscillator_Frequency={[24] 'Oscillator Frequency (GHz)' }; S.Chirp_Points={[1024] 'Number of Chirp points' [1 100000]}; S.Window_Type={ {'{rectwin}','bartlett' 'blackman' 'hamming'} }; S.Start_Frequency={ [100] '' [0 44100]}; S.Stop_Frequency={ [700] '' [0 44100]}; S.Frequency_Unit={ {'{Hz}','m/s' 'km/h' 'mph'} }; SamplingParameters=StructDlg(S,'Sampling Parameters'); if ~isempty(SamplingParameters), set(handles.hboto,'string','Stop','visible','on'); clear CaptureData %Capura de la tarja de so Fs=SamplingParameters.Sampling_Rate; SamplingData.Sampling_Rate=Fs; switch SamplingParameters.Frequency_Unit, case 'Hz', escala=1; TextUnit='Hz'; case 'm/s', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8/f0)/2; TextUnit='m/s'; case 'km/h', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/f0)/2; TextUnit='km/h'; case 'mph', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/1.609344/f0)/2; TextUnit='mph'; end switch SamplingParameters.Window_Type, case 'rectwin', win=window(@rectwin,SamplingParameters.Samples_Number); case 'bartlett', win=window(@bartlett,SamplingParameters.Samples_Number); case 'blackman', win=window(@blackman,SamplingParameters.Samples_Number); case 'hamming', win=window(@hamming,SamplingParameters.Samples_Number); end m = SamplingParameters.Chirp_Points; f1=SamplingParameters.Start_Frequency; f2=SamplingParameters.Stop_Frequency; w = exp(-j*2*pi*(f2-f1)/(m*Fs)); a = exp(j*2*pi*f1/Fs); count=0; while ~strcmp(get(handles.hboto,'string'),'End') SamplingData.Data=wavrecord(SamplingParameters.Samples_Number,Fs,'double'); Z = czt(SamplingData.Data.*win,m,w,a); fz = ((0:length(Z)-1)'*(f2-f1)/length(Z)) + f1; [M,I]=max(abs(Z)); count=count+1; CaptureData.FrequencyDoppler(count)=fz(I); if count==1, figure; h=plot(1:count,CaptureData.FrequencyDoppler*escala); xlabel('Sample');ylabel(TextUnit); else set(h,'XData',1:length(CaptureData.FrequencyDoppler),'YData',CaptureData.FrequencyDoppler*escala); drawnow; end; end; end; % -------------------------------------------------------------------- function About_Callback(hObject, eventdata, handles) % hObject handle to About (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) msgbox('(C) 2008 A.L\E1zaro/D.Girbau'); % -------------------------------------------------------------------- function File_Callback(hObject, eventdata, handles) % hObject handle to File (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Mesura_Callback(hObject, eventdata, handles) % hObject handle to Mesura (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Velocimetre_Callback(hObject, eventdata, handles) % hObject handle to Velocimetre (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function Help_Callback(hObject, eventdata, handles) % hObject handle to Help (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function SaveSample_Callback(hObject, eventdata, handles) % hObject handle to Untitled_1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global SamplingData [filename, pathname] = uiputfile('*.mat', 'Pick an MAT-file'); if isequal(filename,0) | isequal(pathname,0) disp('User pressed cancel') else file=fullfile(pathname, filename); eval(['save ',file,' SamplingData -mat']); end % -------------------------------------------------------------------- function LoadSample_Callback(hObject, eventdata, handles) % hObject handle to Untitled_2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global SamplingData [filename, pathname] = uigetfile('*.mat', 'Pick an MAT-file'); if isequal(filename,0) | isequal(pathname,0) disp('User pressed cancel') else file=fullfile(pathname, filename); load(file,'-mat'); end % -------------------------------------------------------------------- function SaveCaptura_Callback(hObject, eventdata, handles) % hObject handle to SaveCaptura (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global CaptureData [filename, pathname] = uiputfile('*.vel', 'Pick an vel-file'); if isequal(filename,0) | isequal(pathname,0) disp('User pressed cancel') else file=fullfile(pathname, filename); eval(['save ',file,' CaptureData -mat']); end % --- Executes on button press in hboto. function hboto_Callback(hObject, eventdata, handles) % hObject handle to hboto (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global SamplingParameters SamplingData %Si esta en mode sample mode=get(handles.hboto,'string'); if strcmp(mode,'Sample'), %Capura de la tarja de so Fs=SamplingParameters.Sampling_Rate; SamplingData.Data=wavrecord(SamplingParameters.Samples_Number,Fs,'double'); SamplingData.Sampling_Rate=Fs; switch SamplingParameters.Window_Type, case 'rectwin', w=window(@rectwin,SamplingParameters.Samples_Number); case 'bartlett', w=window(@bartlett,SamplingParameters.Samples_Number); case 'blackman', w=window(@blackman,SamplingParameters.Samples_Number); case 'hamming', w=window(@hamming,SamplingParameters.Samples_Number); end figure; subplot(211); t=linspace(0,(SamplingParameters.Samples_Number-1)/Fs,SamplingParameters.Samples_Number)*1e3; %temps en ms plot(t,SamplingData.Data); xlabel('t(ms)'); ylabel('x(t)'); subplot(212); %Positius i negatius %X=fftshift(fft(SamplingData.Data,SamplingParameters.FFT_Points)); %N=length(X); f=Fs*(-N/2:N/2-1)/N; %Frequencies positives nomes X=fft(SamplingData.Data.*w,SamplingParameters.FFT_Points); N=length(X); X=X(1:(N/2)); f=Fs*(0:(N/2-1))/N; switch SamplingParameters.Frequency_Unit, case 'Hz', escala=1; TextUnit='Hz'; case 'm/s', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8/f0)/2; TextUnit='m/s'; case 'km/h', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/f0)/2; TextUnit='km/h'; case 'mph', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/1.609344/f0)/2; TextUnit='mph'; end plot(f*escala,abs(X)); xlabel(TextUnit); ylabel('mag'); [m,I]=max(abs(X)); title(['Maxim ',num2str(f(I)*escala),' ',TextUnit]); else %Mode capture, esperant stop set(handles.hboto,'string','End','visible','off'); end % -------------------------------------------------------------------- function Plot_Callback(hObject, eventdata, handles) % hObject handle to Plot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global SamplingData S.Oscillator_Frequency={[24] 'Oscillator Frequency (GHz)' }; S.FFT_Points={[1024] 'Number of FFT points' [1 100000]}; S.Window_Type={ {'{rectwin}','bartlett' 'blackman' 'hamming'} }; S.Frequency_Unit={ {'{Hz}','m/s' 'km/h' 'mph'} }; SamplingParameters=StructDlg(S,'Sampling Parameters'); Fs=SamplingData.Sampling_Rate; SamplingParameters.Samples_Number=length(SamplingData.Data); switch SamplingParameters.Window_Type, case 'rectwin', w=window(@rectwin,SamplingParameters.Samples_Number); case 'bartlett', w=window(@bartlett,SamplingParameters.Samples_Number); case 'blackman', w=window(@blackman,SamplingParameters.Samples_Number); case 'hamming', w=window(@hamming,SamplingParameters.Samples_Number); end figure; subplot(211); t=linspace(0,(SamplingParameters.Samples_Number-1)/Fs,SamplingParameters.Samples_Number)*1e3; %temps en ms plot(t,SamplingData.Data); xlabel('t(ms)'); ylabel('x(t)'); subplot(212); %Positius i negatius %X=fftshift(fft(SamplingData.Data,SamplingParameters.FFT_Points)); %N=length(X); f=Fs*(-N/2:N/2-1)/N; %Frequencies positives nomes X=fft(SamplingData.Data.*w,SamplingParameters.FFT_Points); N=length(X); X=X(1:(N/2)); f=Fs*(0:(N/2-1))/N; switch SamplingParameters.Frequency_Unit, case 'Hz', escala=1; TextUnit='Hz'; case 'm/s', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8/f0)/2; TextUnit='m/s'; case 'km/h', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/f0)/2; TextUnit='km/h'; case 'mph', f0=SamplingParameters.Oscillator_Frequency*1e9; escala=(3e8*3.6/1.609344/f0)/2; TextUnit='mph'; end plot(f*escala,abs(X)); xlabel(TextUnit); ylabel('mag'); [m,I]=max(abs(X)); title(['Maxim ',num2str(f(I)*escala),' ',TextUnit]); %------------------------------ %_------------------------------- Fs=22050*2; r = audiorecorder(22050*2, 16, 1); record(r); % speak into microphone... pause(r); p = play(r); % listen resume(r); % speak again stop(r); p = play(r); % listen to complete recording DATA = getaudiodata(r, 'int16'); % get data as int16 array plot(DATA) Fs = 44100; y = wavrecord(Fs, Fs, 'int16'); %wavplay(y, Fs); DATA=y; X=fftshift(abs(fft(double(DATA)))); N=length(X); f=Fs*(-N/2:N/2-1)/N;plot(f,X) %---------------------------------------------- %----------------------------------------------- %-Struct function [str,cur_line] = struct2str(s,units,max_width,max_struct_elem, ident_str,total_ident_len,str,cur_line) % % AF 11/6/01 if (exist('units','var') ~= 1) units = struct([]); end if (exist('max_width','var') ~= 1) max_width = Inf; end if (exist('max_struct_elem','var') ~= 1) max_struct_elem = 3; end if (exist('ident_str','var') ~= 1) ident_str = '|'; end if (exist('total_ident_len','var') ~= 1) total_ident_len = 2; end if (exist('str','var') ~= 1) str = repmat({''},400,1); first_call = 1; else first_call = 0; end if (exist('cur_line','var') ~= 1) cur_line = 0; end spacing = 2; fnames = fieldnames(s); fnames_lbl = build_labels(fnames,units); max_lbl_width = size(char(fnames_lbl),2); for i = 1:length(fnames) for j = 1:spacing-1 cur_line = cur_line+1; str{cur_line} = ident_str; end cur_line = cur_line+1; str{cur_line} = ident_str; leading_spaces = repmat('-', 1, total_ident_len -length(ident_str)+max_lbl_width -length(fnames_lbl{i})); str{cur_line} = sprintf('%s%s%s: ', str{cur_line} ,leading_spaces, fnames_lbl{i}); x = getfield(s,fnames{i}); %% recursive call for sub-structures if (isstruct(x)) new_ident_len = total_ident_len + max_lbl_width+2; new_ident_str = [ident_str repmat(' ',1,new_ident_len-2 - length(ident_str) - ceil(length(fnames_lbl{i})/2)) '|']; for xi = 1:min(length(x),max_struct_elem) if (isfield(units,fnames{i})) sub_units = getfield(units,fnames{i}); else sub_units = struct([]); end [str,cur_line] = struct2str(x(xi),sub_units,max_width,max_struct_elem, new_ident_str,new_ident_len,str,cur_line); cur_line = cur_line+1; str{cur_line} = ident_str; end if (length(x) > max_struct_elem) dotted_str = [ident_str repmat(' ',1,new_ident_len-2 - length(ident_str) - ceil(length(fnames_lbl{i})/2)) ':']; for dot_i = 1:2 cur_line = cur_line+1; str{cur_line} = dotted_str; end end else xstr = element2str(x,max_width-max_lbl_width-2); str{cur_line} = sprintf('%s%s', str{cur_line}, xstr); end end if (first_call) str = str(1:cur_line); end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% SUB FUNCTIONS %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fnames_lbl = build_labels(fnames,units); % fnames_lbl = strrep(fnames,'_',' '); f_units = fieldnames(units); v_units = struct2cell(units); for i = 1:length(f_units) if (ischar(v_units{i}) & ~isempty(v_units{i})) index = strmatch(f_units{i},fnames,'exact'); if (~isempty(index)) fnames_lbl{index} = strrep(v_units{i},'*',fnames_lbl{index}); % fnames_lbl{index} = [fnames_lbl{index} ' (' v_units{i} ')']; end end end return; % function fnames_lbl = build_labels(fnames,f_units); % % % fnames_lbl = strrep(fnames,'_',' '); % for i = 1:min(length(fnames_lbl),length(f_units)) % if (ischar(f_units{i}) & ~isempty(f_units{i})) % fnames_lbl{i} = [fnames_lbl{i} ' (' f_units{i} ')']; % end % end % return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function xstr = element2str(x,max_width) if (exist('max_width','var') ~= 1) max_width = Inf; end switch (class(x)) case 'char' if (length(x) < max_width-2) xstr = ['''' x '''']; else xstr = ['''' x(1:max_width-4) '...''']; end case {'double' 'sparse'} if (isempty(x)) xstr = '[]'; elseif (ndims(x) > 2 | min(size(x)) >1 | length(x) >150) dims = size(x); xstr = ['[' sprintf('%dx',dims(1:end-1)) sprintf('%d',dims(end)) ' ' class(x) ']']; else % x is a vector if (size(x,2) == 1) sep = ' ; '; else sep = ' '; end if (length(x) == 1) xstr = num2str(x); else xstr = ['[' num2str(x(1))]; for ix = 2:length(x) xstr = [xstr sep num2str(x(ix))]; end xstr = [xstr ']']; end if (length(xstr) > max_width) xstr = [xstr(1:max_width-4) '...]']; end end case 'cell' xstr = '{'; if (isempty(x)) xstr = '{}'; elseif (ndims(x) > 2 | min(size(x)) >1) dims = size(x); xstr = ['{' sprintf('%dx',dims(1:end-1)) sprintf('%d',dims(end)) ' cell}']; else % x is a cell vector if (size(x,2) == 1) sep = ' ; '; else sep = ' '; end xstr = ['{' element2str(x{1},max_width/3)]; for ix = 2:length(x) xstr = [xstr sep element2str(x{ix},max_width/3)]; end xstr = [xstr '}']; if (length(xstr) > max_width) xstr = [xstr(1:max_width-4) '...}']; end end case 'function_handle' xstr = element2str(['@' func2str(x)],max_width); end
Comments