R| ifelse、which、%in%的用法

 ref:

  	
在R学习过程中,遇到了ifelse、which、%in%,下面分别举例,说明他们的用法。
1、ifelse
ifelse(test, yes, no)
test为真,输出yes值,否则输出no值。
举例如下:
> x <- c(1,1,1,0,0,1,1)
> ifelse(x != 1, 1, 0) #若果x的值不等于1,输出1,否则输出0
[1] 0 0 0 1 1 0 0

2、which
用法which(test)。
返回test为真值的位置(指针)。
举例如下:
> which(x!=1) #返回x中不等于1的变量值得位置
[1] 4 5
> which(c(T,F,T)) #返回c(T,F,T)中为TURE值的位置。
[1] 1 3
> which(c(1,0,1)) #只对T, F做判断。
Error in which(c(1, 0, 1)) : argument to 'which' is not logical

3、%in%
用法 a %in% table
a值是否包含于table中,为真输出TURE,否者输出FALSE
例如
> x %in% 1
[1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE
> x %in% c(1, 0)
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE
> x %in% c(1, 2)
[1]  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE


联合使用
> ifelse(x %in% 1, 1, 0) #若x的值包含在1里面,输出1,否者输出0
[1] 1 1 1 0 0 1 1
> ifelse(x %in% 1, 'yes', 'no') #若x的值包含在1里面,输出yes,否者输出no
[1] "yes" "yes" "yes" "no"  "no"  "yes" "yes"
> which(x %in% 1) 输出x包含在1中值的位置
[1] 1 2 3 6 7
> y <- c(2, 1, 3, 4)
> z <- c(1, 4)
> ifelse(y %in% z, which(y==z), 0 ) ##若y的值包含在z里面,输出y==z的位置,否者输出0
[1] 0 2 0 4
> ifelse(y %in% z, which(y==z), 0 ) ##若y的值包含在z里面,输出y==z的位置,否者输出0,
                                     #此例中没有找到y==z的值, 输出为NA。
[1] NA  0  0 NA
> ifelse(y %in% z, 1, 0 )
[1] 1 0 0 1

 

写一个调用函数matlab代码关于function [T,Xinit] = tucker_sym(S,R,varargin) %TUCKER_SYM Symmetric Tucker approximation. % % T = TUCKER_SYM(S,R) computes the best rank-(R,R,...,R) approximation of % the symmetric tensor S, according to the specified dimension R. The % result returned in T is a ttensor (with all factors equal), i.e., % T = G x_1 X x_2 X ... x_N X where X is the optimal factor matrix and G % is the corresponding core. % % T = TUCKER_SYM(S,R,'param',value,...) specifies optional parameters and % values. Valid parameters and their default values are: % 'tol' - Tolerance on difference in X {1.0e-10} % 'maxiters' - Maximum number of iterations {1000} % 'init' - Initial guess [{'random'}|'nvecs'|cell array] % 'printitn' - Print fit every n iterations {1} % 'return' - First return argument is T or X [{'ttensor'},'matrix'] % % [T,X0] = TUCKER_SYM(...) also returns the initial guess. % % See also TUCKER_SYM. % % Reference: Phillip A. Regalia, Monotonically Convergent Algorithms for % Symmetric Tensor Approximation, Linear Algebra and its Applications % 438(2):875-890, 2013, http://dx.doi.org/10.1016/j.laa.2011.10.033. % %MATLAB Tensor Toolbox. Copyright 2018, Sandia Corporation. %% Input checking if ~issymmetric(S) error('S must be symmetric'); end if numel(R) ~= 1 error('R must be a scalar'); end N = ndims(S); D = size(S,1); %% Set algorithm parameters from input or by using defaults params = inputParser; params.addParameter('tol',1e-10,@isscalar); params.addParameter('maxiters',1000,@(x) isscalar(x) & x > 0); params.addParameter('init', 'random'); params.addParameter('printitn',1,@isscalar); params.addParameter('return','ttensor'); params.parse(varargin{:}); %% Copy from params object tol = params.Results.tol; maxiters = params.Results.maxiters; init = params.Results.init; printitn = params.Results.printitn; %% Error checking % Error checking on maxiters if maxiters < 0 error('OPTS.maxiters must be positive'); end %% Set up and error checking on initial guess for U. if isnumeric(init) Xinit = init; if ~isequal(size(Xinit),[D R]) error('OPTS.init is the wrong size'); end else if strcmp(init,'random') Xinit = rand(D,R); elseif strcmp(init,'nvecs') || strcmp(init,'eigs') % Compute an orthonormal basis for the dominant % Rn-dimensional left singular subspace of % X_(n) (1 <= n <= N). fprintf('Computing %d leading e-vectors.\n',R); Xinit = nvecs(S,1,R); else error('The selected initialization method is not supported'); end end %% Set up for iterations - we ensure that X is orthogonal X = Xinit; [X,~] = qr(X,0); % Roughly the same tolerance as is used by pinv svdtol = D^(N-1) * norm(S) * eps(1.0); if printitn > 0 fprintf('\nSymmetric Tucker:\n'); end %% Main Loop: Iterate until convergence Xcell = cell(N,1); for iter = 1:maxiters Xold = X; % For the remainder tensor [Xcell{:}] = deal(X); Rem = ttm(S, Xcell, -1, 't'); Rem = double(tenmat(Rem, 1)); % Form gradient % NOTE: We use the SVD directly rather than PINV, which could be % invoked by the line: X = 2*N*Rem*pinv(Rem)*X; [UU,SS,~] = svd(Rem,0); ii = find(diag(SS) > svdtol, 1, 'last'); UU = UU(:,1:ii); X = 2*N*UU*(UU'*X); % Update X [X,~] = qr(X,0); % Check for convergence fit = norm(X-Xold)/norm(X); % Check for convergence if (fit < tol) break; end % Print results if mod(iter,printitn)==0 fprintf(' Iter %2d: rel. change in X = %e\n', iter, fit); end end % Print final result if (printitn > 0) && (iter < maxiters) fprintf(' Iter %2d: rel. change in X = %e\n', iter, fit); end % Do they want just the matrix or the full tensor back? if strcmpi(params.Results.return,'matrix') T = X; else [Xcell{:}] = deal(X); core = ttm(S, Xcell, 1:N, 't'); T = ttensor(core, Xcell); end
11-21
function varargout = advisor(varargin) % advisor Application M-file for advisor.fig % FIG = advisor launch advisor GUI. % advisor('callback_name', ...) invoke the named callback. % % ADVISOR Advanced Vehicle Simulator % % This function opens the first graphical user interface (GUI) into % the program ADVISOR. % % The ADVISOR program is designed to assist in testing different % vehicle configurations using standard and custom driving cycles or % test procedures. % % For help in running ADVISOR please use the help buttons found on % each user interface which links to the documentation pages. If you still % need help or have helpful suggestions for improvement please email: % advisor@nrel.gov % % Last Modified by GUIDE v2.0 21-Mar-2002 15:12:42 if nargin == 0 % LAUNCH GUI global vinf %----------------------------------------------------------- %if ADVISOR is running then don't start another one, just %bring the current ADVISOR figure to the top figure_tags={'advisor_figure';'input_figure';'execute_figure';'results_figure';... 'rw_results_figure';'parametric_results_figure';'j1711_results_figure';... 'city_hwy_results_figure';'ftp_results_figure'}; for i=1:size(figure_tags) if ~isempty(findobj('tag',figure_tags{i})) figure(findobj('tag',figure_tags{i})); return end end %------------------------------------------------------------- advisor('set_path') %-------------------------------------------------- %clear the workspace evalin('base','clear'); evalin('base','global vinf') %set units to 'us' if not defined if ~exist('vinf.units') vinf.units='us'; end hwait=waitbar(0,'loading startup figure'); try waitbar(.5) end %add some sound if user's system can play sound try load list_optionlist.mat; %loads list_optionlist and list_def if findstr(lower(list_def),'truck') [advisor_sound,fs]=wavread('truckwelcome.wav'); else [advisor_sound,fs]=wavread('advisor.wav'); end sound(advisor_sound,fs) end %--------------------------------------------------- fig = openfig(mfilename,'new'); %'reuse' wasn't working when SOC figure was up %fig = openfig(mfilename,'reuse'); % Generate a structure of handles to pass to callbacks, and store it. handles = guihandles(fig); guidata(fig, handles); if nargout > 0 varargout{1} = fig; end %------------------------------------------------------- %adjust the figure appropriately [ver,date]=advisor_ver('info'); set(findobj('tag','advisor_figure'),'Name',[ver ' ' date]) %set the units radio buttons appropriately set(findobj('tag','metric_radiobutton'),'value',strcmp(vinf.units,'metric')) set(findobj('tag','us_radiobutton'),'value',strcmp(vinf.units,'us')) %set the optionlist popupmenu advisor('set_optionlist_popup') %set everything normalized and set the figure size and center it h=findobj('type','uicontrol'); g=findobj('type','axes'); set([h;g],'units','normalized') screensize=get(0,'screensize'); if screensize(3)<1024 uiwait(warndlg({'ADVISOR does not work well at resolutions lower than 1024x768. Please increase resolution or proceed with caution!'},... 'ADVISOR: Low Resolution Warning','modal')) end %test for large fonts and give warning if they are large. figh=figure('visible','off'); test_string='test string'; handle_text=text(0,0,test_string); set(handle_text,'units','pixels') extent=get(handle_text,'extent');% 0 -9 60 18 close(figh); if extent(3)>61 uiwait(warndlg({'ADVISOR does not work well with large fonts. Please change your display settings to small fonts or proceed with caution!'},... 'ADVISOR: Low Resolution Warning','modal')) end im_width=640;%this is the width of the image im_height=474; left=screensize(3)/2-im_width/2; bottom=screensize(4)/2-im_height/2; set(gcf,'position',[left bottom im_width im_height]);% set(gcf,'resize','off') %set the figure back on after everything is drawn set(gcf,'visible','on'); advisor_ver waitbar(1) close(hwait); %close the waitbar adv_dir=strrep(which('advisor'),'\advisor.m',''); imagedata = imread([adv_dir '\gui_graphics\Splash_Screen_car.jpg']); h=image(imagedata); set(h,'ButtonDownFcn','advisor(''play_movie'')'); advisor('play_movie') elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK try if (nargout) [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard else feval(varargin{:}); % FEVAL switchyard end catch disp(lasterr); end end %| ABOUT CALLBACKS: %| GUIDE automatically appends subfunction prototypes to this file, and %| sets objects' callback properties to call them through the FEVAL %| switchyard above. This comment describes that mechanism. %| %| Each callback subfunction declaration has the following form: %| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN) %| %| The subfunction name is composed using the object's Tag and the %| callback type separated by '_', e.g. 'slider2_Callback', %| 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'. %| %| H is the callback object's handle (obtained using GCBO). %| %| EVENTDATA is empty, but reserved for future use. %| %| HANDLES is a structure containing handles of components in GUI using %| tags as fieldnames, e.g. handles.figure1, handles.slider2. This %| structure is created at GUI startup using GUIHANDLES and stored in %| the figure's application data using GUIDATA. A copy of the structure %| is passed to each callback. You can store additional information in %| this structure at GUI startup, and you can change the structure %| during callbacks. Call guidata(h, handles) after changing your %| copy to replace the stored original so that subsequent callbacks see %| the updates. Type "help guihandles" and "help guidata" for more %| information. %| %| VARARGIN contains any extra arguments you have passed to the %| callback. Specify the extra arguments by editing the callback %| property in the inspector. By default, GUIDE sets the property to: %| <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo)) %| Add any extra arguments after the last argument, before the final %| closing parenthesis. % -------------------------------------------------------------------- function varargout = Copyright_button_Callback(h, eventdata, handles, varargin) copyright % -------------------------------------------------------------------- function varargout = Start_button_Callback(h, eventdata, handles, varargin) global vinf close(gcbf); evalin('base','global vinf'); gui_input_open('defaults'); % -------------------------------------------------------------------- function varargout = edit_optionlist() edit_profiles % -------------------------------------------------------------------- function varargout = Profile_Popup_Callback(h, eventdata, handles, varargin) current_selection_str=gui_current_str('Profile_Popup'); if strcmp(current_selection_str,'edit list') advisor('edit_optionlist') return end global vinf vinf.optionlist.name=current_selection_str; load list_optionlist.mat list_def=current_selection_str; p=which('list_optionlist.mat'); save(p,'list_def','list_optionlist'); %--------------------------------------------------------------------- function varargout = set_optionlist_popup load list_optionlist.mat; %loads list_optionlist and list_def set(findobj('tag','Profile_Popup'),'string',list_optionlist) index=strmatch(list_def, list_optionlist, 'exact'); set(findobj('tag','Profile_Popup'),'value',index); global vinf vinf.optionlist.name=list_def; % -------------------------------------------------------------------- function varargout = Help_button_Callback(h, eventdata, handles, varargin) web(['file:\\\' which('advisor_doc.htm')],'-browser'); % -------------------------------------------------------------------- function varargout = Exit_button_Callback(h, eventdata, handles, varargin) close(gcbf) % -------------------------------------------------------------------- function varargout = list_popup_Callback(h, eventdata, handles, varargin) %---------------------------------------------------- function set_path() %------------------Add ADVISOR directories to the MATLAB path------------- % Add the appropriate paths based on where advisor.m is found with the which command (This % defines the main ADVISOR directory) % % NOTE: paths will only be added with the addpath command if they don't already exist. % If new directories were added to the path (using addpath), a 1 will be returned % otherwise a 0 will be returned. % % SetAdvisorPath can accept a comma separated list of arguments. The arguments should be % the name of an existing directory. Non-existing directories will not be created. % path_added=SetAdvisorPath; % external function that contains necessary path information %find out if user wants to save the path changes. if path_added==1 ButtonName=questdlg('The Matlab path has been updated with ADVISOR directories for this Matlab session. Would you like to save the new path for future Matlab sessions? Note: Using VisualDoc optimization requires the path to be saved. ', ... 'ADVISOR path setting', ... 'Yes','No','Yes'); switch ButtonName, case 'Yes', result=path2rc; %path2rc saves the current path to pathdef.m (Both are MATLAB files-- not ADVISOR files) if result==0 disp('ADVISOR Directories were successfully added to the Matlab Path. See Path browser for path information.'); else disp('Not successful. ADVISOR directories were not successfully saved in the Matlab Path.'); end case 'No', end % switch end; %if path_added=1; % -------------------------------------------------------------------- function varargout = Load_Results_Callback(h, eventdata, handles, varargin) global vinf if ~exist('varargin') % no user-specified filename provided [name, path]=uigetfile('*.mat'); %user input for mat name of saved simulation elseif isempty(varargin) [name, path]=uigetfile('*.mat'); %user input for mat name of saved simulation else % user-specified filename provided path_name=varargin{1}; % break argument into the path and filename parts idx=strfind(path_name,'\'); if isempty(idx) idx=strfind(path_name,'/'); end if isempty(idx) name=path_name; path=''; else name=path_name((max(idx)+1):end); path=path_name(1:max(idx)); end end %if no file is selected(ie. figure is cancelled) %then exit(or return) out of this function if name==0 return end evalin('base','clear all') evalin('base',['load ''', path, name,'''']); close(gcbf); global vinf; if strcmp(vinf.parametric.run,'off') ResultsFig; else parametric_gui; end %--------------------------------------------------------------------- function metric_radiobutton_Callback(h, eventdata, handles, varargin) global vinf vinf.units='metric'; set(findobj('tag','us_radiobutton'),'value',0); set(findobj('tag','metric_radiobutton'),'value',1); %--------------------------------------------------------------------- function us_radiobutton_Callback(h, eventdata, handles, varargin) global vinf vinf.units='us'; set(findobj('tag','metric_radiobutton'),'value',0); set(findobj('tag','us_radiobutton'),'value',1); %--------------------------------------------------------------------- function play_movie() try adv_dir=strrep(which('advisor'),'\advisor.m',''); imagenames={'car2truck001.gif'; 'car2truck002.gif'; 'car2truck003.gif'; 'car2truck004.gif'; 'car2truck005.gif'; 'car2truck006.gif'; 'car2truck007.gif'; 'car2truck008.gif'; 'car2truck009.gif'; 'car2truck010.gif'; 'car2truck011.gif'; 'car2truck012.gif'; 'car2truck013.gif'; 'car2truck014.gif'; 'car2truck015.gif'}; for i=1:length(imagenames) [X,map]=imread([adv_dir '\gui_graphics\' imagenames{i}]); M(i)=im2frame(X,map); end loc=[36 206 0 0]; N=[-2 1 1 1 1 1 1 1:15 15 15 15 15 15 15 15]; movie(M,N,8,loc) end function LoadVehicle(filename) % allows user to start ADVISOR with a specific saved vehicle other than the default if ~exist('filename') filename='PARALLEL_defaults_in'; end if evalin('base',['~exist(''',filename,'.m'')']) disp(['File ',filename,'.m not found.']) else global vinf vinf.units='us'; gui_input_open(filename) end return function LoadResults(filename) % allows user to start ADVISOR with a specific results file from the command line if exist('filename') if evalin('base',['~exist(''',filename,'.mat'')']) disp(['File ',filename,'.mat not found.']) else advisor('Load_Results_Callback',[],[],[],filename) end end return % Revision History % 041802:tm added call to SetAdvisorPath external function and removed common code from this file % 041802:tm added statements to the Load_Results_Callback function to allow the user to specify a % results file to load from the command line % 041802:tm added function to allow user to load a specific vehicle from the command line % 041802:tm added function to allow user to load a specific results file from the command line 怎么修改可以让advisor2002适配MATLAB2024a
08-09
function [T,Xinit] = tucker_sym(S,R,varargin) %TUCKER_SYM Symmetric Tucker approximation. % % T = TUCKER_SYM(S,R) computes the best rank-(R,R,...,R) approximation of % the symmetric tensor S, according to the specified dimension R. The % result returned in T is a ttensor (with all factors equal), i.e., % T = G x_1 X x_2 X ... x_N X where X is the optimal factor matrix and G % is the corresponding core. % % T = TUCKER_SYM(S,R,'param',value,...) specifies optional parameters and % values. Valid parameters and their default values are: % 'tol' - Tolerance on difference in X {1.0e-10} % 'maxiters' - Maximum number of iterations {1000} % 'init' - Initial guess [{'random'}|'nvecs'|cell array] % 'printitn' - Print fit every n iterations {1} % 'return' - First return argument is T or X [{'ttensor'},'matrix'] % % [T,X0] = TUCKER_SYM(...) also returns the initial guess. % % See also TUCKER_SYM. % % Reference: Phillip A. Regalia, Monotonically Convergent Algorithms for % Symmetric Tensor Approximation, Linear Algebra and its Applications % 438(2):875-890, 2013, http://dx.doi.org/10.1016/j.laa.2011.10.033. % %MATLAB Tensor Toolbox. %Copyright 2015, Sandia Corporation. % This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others. % http://www.sandia.gov/~tgkolda/TensorToolbox. % Copyright (2015) Sandia Corporation. Under the terms of Contract % DE-AC04-94AL85000, there is a non-exclusive license for use of this % work by or on behalf of the U.S. Government. Export of this data may % require a license from the United States Government. % The full license terms can be found in the file LICENSE.txt %% Input checking if ~issymmetric(S) error('S must be symmetric'); end if numel(R) ~= 1 error('R must be a scalar'); end N = ndims(S); D = size(S,1); %% Set algorithm parameters from input or by using defaults params = inputParser; params.addParameter('tol',1e-10,@isscalar); params.addParameter('maxiters',1000,@(x) isscalar(x) & x > 0); params.addParameter('init', 'random'); params.addParameter('printitn',1,@isscalar); params.addParameter('return','ttensor'); params.parse(varargin{:}); %% Copy from params object tol = params.Results.tol; maxiters = params.Results.maxiters; init = params.Results.init; printitn = params.Results.printitn; %% Error checking % Error checking on maxiters if maxiters < 0 error('OPTS.maxiters must be positive'); end %% Set up and error checking on initial guess for U. if isnumeric(init) Xinit = init; if ~isequal(size(Xinit),[D R]) error('OPTS.init is the wrong size'); end else if strcmp(init,'random') Xinit = rand(D,R); elseif strcmp(init,'nvecs') || strcmp(init,'eigs') % Compute an orthonormal basis for the dominant % Rn-dimensional left singular subspace of % X_(n) (1 <= n <= N). fprintf('Computing %d leading e-vectors.\n',R); Xinit = nvecs(S,1,R); else error('The selected initialization method is not supported'); end end %% Set up for iterations - we ensure that X is orthogonal X = Xinit; [X,~] = qr(X,0); % Roughly the same tolerance as is used by pinv svdtol = D^(N-1) * norm(S) * eps(1.0); if printitn > 0 fprintf('\nSymmetric Tucker:\n'); end %% Main Loop: Iterate until convergence Xcell = cell(N,1); for iter = 1:maxiters Xold = X; % For the remainder tensor [Xcell{:}] = deal(X); Rem = ttm(S, Xcell, -1, 't'); Rem = double(tenmat(Rem, 1)); % Form gradient % NOTE: We use the SVD directly rather than PINV, which could be % invoked by the line: X = 2*N*Rem*pinv(Rem)*X; [UU,SS,~] = svd(Rem,0); ii = find(diag(SS) > svdtol, 1, 'last'); UU = UU(:,1:ii); X = 2*N*UU*(UU'*X); % Update X [X,~] = qr(X,0); % Check for convergence fit = norm(X-Xold)/norm(X); % Check for convergence if (fit < tol) break; end % Print results if mod(iter,printitn)==0 fprintf(' Iter %2d: rel. change in X = %e\n', iter, fit); end end % Print final result if (printitn > 0) && (iter < maxiters) fprintf(' Iter %2d: rel. change in X = %e\n', iter, fit); end % Do they want just the matrix or the full tensor back? if strcmpi(params.Results.return,'matrix') T = X; else [Xcell{:}] = deal(X); core = ttm(S, Xcell, 1:N, 't'); T = ttensor(core, Xcell); end写一个调用函数的matlab的代码
11-20
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值