matlab displayname中输入my name显示为什么颜色

Default Arguments in Matlab - Stack Overflow
Join Stack Overflow to learn, share knowledge, and build your career.
or sign in with
Is it possible to have default arguments in Matlab?
For instance, here:
function wave(a,b,n,k,T,f,flag,fTrue=inline('0'))
I would like to have the true solution be an optional argument to the wave function.
If it is possible, can anyone demonstrate the proper way to do this?
Currently, I am trying what I posted above and I get:
??? Error: File: wave.m Line: 1 Column: 37
The expression to the left of the equals sign is not a valid target for an assignment.
1,08151625
As far as I know, there isn't a direct way to do this like you've attempted.
The usual approach is to use varargs and check against the number of args.
Something like:
function f(arg1,arg2,arg3)
if nargin & 3
'some default'
There are a few fancier things you can do with isempty, etc., and you might want to look at matlab central for some packages that bundle these sorts of things.
glad that helped.
you might have a look at varargin,
nargchk, etc. they're useful functions for this sort of thing.
varargs allow you to leave a variable number of final arguments, but this doesn't get you around the problem of default values for some/all of them.
6,61612227
I've used the
object to deal with setting default options. Matlab won't accept the python-like format you specified in the question, but you should be able to call the function like this:
wave(a,b,n,k,T,f,flag,'fTrue',inline('0'))
After you define the wave function like this:
function wave(a,b,n,k,T,f,flag,varargin)
i_p = inputP
i_p.FunctionName = 'WAVE';
i_p.addRequired('a',@isnumeric);
i_p.addRequired('b',@isnumeric);
i_p.addRequired('n',@isnumeric);
i_p.addRequired('k',@isnumeric);
i_p.addRequired('T',@isnumeric);
i_p.addRequired('f',@isnumeric);
i_p.addRequired('flag',@isnumeric);
i_p.addOptional('ftrue',inline('0'),1);
i_p.parse(a,b,n,k,T,f,flag,varargin{:});
Now the values passed into the function are available through i_p.Results. Also, I wasn't sure how to validate that the parameter passed in for ftrue was actually an inline function so left the validator blank.
63.4k22119221
Another slightly less hacky way is
function output = fun(input)
if ~exist('input','var'), input='BlahBlahBlah'; end
Yes, it might be really nice to have the capability to do as you have written. But it is not possible in MATLAB. Many of my utilities that allow defaults for the arguments tend to be written with explicit checks in the beginning like this:
if (nargin&3) or isempty(myParameterName)
MyParameterName = defaultV
elseif (.... tests for non-validity of the value actually provided ...)
error('The sky is falling!')
Ok, so I would generally apply a better, more descriptive error message. See that the check for an empty variable allows the user to pass in an empty pair of brackets, [], as a placeholder for a variable that will take on its default value. The author must still supply the code to replace that empty argument with its default value though.
My utilities that are more sophisticated, with MANY parameters, all of which have default arguments, will often use a property/value pair interface for default arguments. This basic paradigm is seen in the handle graphics tools in matlab, as well as in optimset, odeset, etc.
As a means to work with these property/value pairs, you will need to learn about varargin, as a way of inputing a fully variable number of arguments to a function. I wrote (and posted) a utility to work with such property/value pairs, . It helps you to convert property/value pairs into a matlab structure. It also enables you to supply default values for each parameter. Converting an unwieldy list of parameters into a structure is a VERY nice way to pass them around in MATLAB.
This is my simple way to set default values to a function, using "try":
function z = myfun (a,varargin)
%% Default values
b = varargin{1};
c = varargin{2};
d = varargin{3};
e = varargin{4};
%% Calculation
z = a * b * c * d *
I've found that the
function can be very helpful.
56.7k35587
There is also a 'hack' that can be used although it might be removed from matlab at some point:
Function eval actually accepts two arguments of which the second is run if an error occurred with the first.
Thus we can use
function output = fun(input)
eval('', 'input = 1;');
to use value 1 as default for the argument
After becoming aware of
(thanks to
I wrote two functions to finally obtain a very simple calling structure:
setParameterDefault('fTrue', inline('0'));
Here's the listing:
function setParameterDefault(pname, defval)
% setParameterDefault(pname, defval)
% Author: Tobias Kienzler (https://stackoverflow.com/users/321973)
% sets the parameter NAMED pname to the value defval if it is undefined or
if ~isParameterDefined('pname')
error('paramDef:noPname', 'No parameter name defined!');
elseif ~isvarname(pname)
error('paramDef:pnameNotChar', 'pname is not a valid varname!');
elseif ~isParameterDefined('defval')
error('paramDef:noDefval', ['No default value for ' pname ' defined!']);
% isParameterNotDefined copy&pasted since evalin can't handle caller's
% caller...
if ~evalin('caller',
['exist(''' pname ''', ''var'') && ~isempty(' pname ')'])
callername = evalin('caller', 'mfilename');
warnMsg = ['Setting ' pname ' to default value'];
if isscalar(defval) || ischar(defval) || isvector(defval)
warnMsg = [warnMsg ' (' num2str(defval) ')'];
warnMsg = [warnMsg '!'];
warning([callername ':paramDef:assigning'], warnMsg);
assignin('caller', pname, defval);
function b = isParameterDefined(pname)
% b = isParameterDefined(pname)
% Author: Tobias Kienzler (https://stackoverflow.com/users/321973)
% returns true if a parameter NAMED pname exists in the caller's workspace
% and if it is not empty
b = evalin('caller',
['exist(''' pname ''', ''var'') && ~isempty(' pname ')']) ;
9,3591574151
I believe I found quite a nifty way to deal with this issue, taking up only three lines of code (barring line wraps). The following is lifted directly from a function I am writing, and it seems to work as desired:
defaults = {50/6,3,true,false,[375,20,50,0]}; %set all defaults
defaults(1:nargin-numberForcedParameters) = %overload with function input
[sigma,shifts,applyDifference,loop,weights] = ...
defaults{:}; %unfold the cell struct
Just thought I'd share it.
I am confused nobody has pointed out
by Loren, one of Matlab's developers. The approach is based on varargin and avoids all those endless and painfull if-then-else or switch cases with convoluted conditions. When there are a few default values, the effect is dramatic. Here's an example from the linked blog:
function y = somefun2Alt(a,b,varargin)
% Some function that requires 2 inputs and has some optional inputs.
% only want 3 optional inputs at most
numvarargs = length(varargin);
if numvarargs & 3
error('myfuns:somefun2Alt:TooManyInputs', ...
'requires at most 3 optional inputs');
% set defaults for optional inputs
optargs = {eps 17 @magic};
% now put these defaults into the valuesToUse cell array,
% and overwrite the ones specified in varargin.
optargs(1:numvarargs) =
% [optargs{1:numvarargs}] = varargin{:};
% Place optional args in memorable variable names
[tol, mynum, func] = optargs{:};
If you still don't get it, then try reading the entire blog post by Loren. I have written a follow up
which deals with missing positional default values. I mean that you could write something like:
somefun2Alt(a, b, '', 42)
and still have the default eps value for the tol parameter (and @magic callback for func of course). Loren's code allows this with a slight but tricky modification.
Finally, just a few advantages of this approach:
Even with a lot of defaults the boilerplate code doesn't get huge (as opposed to the family of if-then-else approaches, which get longer with each new default value)
All the defaults are in one place. If any of those need to change, you have just one place to look at.
Trooth be told, there is a disadvantage too. When you type the function in Matlab shell and forget its parameters, you will see an unhelpful varargin as a hint. To deal with that, you're advised to write a meaningful usage clause.
This is more or l I've only got passing experience...
function my_output = wave ( a, b, n, k, T, f, flag, varargin )
optargin = numel(varargin);
fTrue = inline('0');
if optargin & 0
fTrue = varargin{1};
% code ...
110k13224324
Matlab doesn't provide a mechanism for this, but you can construct one in userland code that's terser than inputParser or "if nargin & 1..." sequences.
function varargout = getargs(args, defaults)
%GETARGS Parse function arguments, with defaults
% args is varargin from the caller. By convention, a [] means "use default".
% defaults (optional) is a cell vector of corresponding default values
if nargin & 2;
defaults = {}; end
varargout = cell(1, nargout);
for i = 1:nargout
if numel(args) &= i && ~isequal(args{i}, [])
varargout{i} = args{i};
elseif numel(defaults) &= i
varargout{i} = defaults{i};
Then you can call it in your functions like this:
function y = foo(varargin)
% y = foo(a, b, c, d, e, f, g)
d, e, f, g] = getargs(varargin,...
{1, 14, 'dfltc'});
The formatting is a convention that lets you read down from parameter names to their default values. You can extend your getargs() with optional parameter type specifications (for error detection or implicit conversion) and argument count ranges.
There are two drawbacks to this approach. First, it's slow, so you don't want to use it for functions that are called in loops. Second, Matlab's function help - the autocompletion hints on the command line - don't work for varargin functions. But it is pretty convenient.
17.2k33765
you might want to use the parseparams the usage would look like:
function output = wave(varargin);
% comments, etc
[reg, props] = parseparams(varargin);
ctrls = cell2struct(props(2:2:end),props(1:2:end),2);
%yes this is ugly!
a = reg{1};
b = reg{2};
fTrue = ctrl.fT
1,29831220
function f(arg1, arg2, varargin)
arg3 = default3;
arg4 = default4;
for ii = 1:length(varargin)/2
if ~exist(varargin{2*ii-1})
error(['unknown parameter: ' varargin{2*ii-1}]);
eval([varargin{2*ii-1} '=' varargin{2*ii}]);
e.g. f(2,4,'c',3) causes the parameter c to be 3.
9,3591574151
if you would use octave you could do it like this - but sadly matlab does not support this possibility
function hello (who = "World")
printf ("Hello, %s!\n", who);
endfunction
(taken from the )
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Upcoming Events
ends Mar 27
Stack Overflow works best with JavaScript enabled891被浏览469,143分享邀请回答zhidao.baidu.com/question/.html26883 条评论分享收藏感谢收起9728 条评论分享收藏感谢收起Math. Graphics. Programming.
Whether you’re analyzing data, developing algorithms, or
creating models, MATLAB is designed for the way you think
and the work you do.
Millions of Engineers and Scientists Trust MATLAB
MATLAB(R) combines a desktop environment tuned for iterative analysis and design processes with a programming language that expresses matrix and array mathematics directly.
Professionally Built
MATLAB toolboxes are professionally developed, rigorously tested, and fully documented.
With Interactive Apps
MATLAB apps let you see how different algorithms work with your data. Iterate until you’ve got the results you want, then automatically generate a MATLAB program to reproduce or automate your work.
And the Ability to Scale
Scale your analyses to run on clusters, GPUs, and clouds with only minor code changes. There’s no need to rewrite your code or learn big data programming and out-of-memory techniques.
Take Your Ideas Beyond Research to Production
Deploy to Enterprise Applications
MATLAB code is production ready, so you can go directly to your cloud and enterprise systems, and integrate with data sources and business systems.
Run on Embedded Devices
Automatically convert MATLAB algorithms to C/C++, HDL, and CUDA code to run on embedded devices.
Integrate with Model-Based Design
MATLAB works with Simulink to support Model-Based Design, which is used for multidomain simulation, automatic code generation, and test and verification of embedded systems.
Explore MATLAB Solutions for:
Explore how to use MATLAB for big data, machine learning, and production analytics.
Discover how MATLAB can help you develop algorithms and perform full wireless system simulation.
Get a Free Trial
30 days of exploration at your fingertips.
Ready to Buy?
Purchase MATLAB and explore related products.
Are You a Student?
Get MATLAB and Simulink student software.
Engineers and Scientists Worldwide Rely on MATLAB
“As a process engineer I had no experience with neural networks or machine learning. I couldn’t have done this in C or Python. It would’ve taken too long to find, validate, and integrate the right packages.”
Emil Schmitt-Weaver, Development Engineer
“MATLAB is the language used by virtually every team in the world that designs gravitational wave detectors… I look forward to exploring the data from each new detection in MATLAB.”
Matthew Evans, Assistant Professor of Physics
Delphi Automotive
“MATLAB is my preferred tool because it speeds algorithm design and improvement. I can generate C code that is reliable, efficient, and easy for software engineers to integrate within a larger system.”
Liang Ma, Systems Engineer
Select Your Country
Choose your country to get translated content where available and see local events and
offers. Based on
your location, we recommend that you select: .
You can also select a location from the following list:
(Fran?ais)
(Italiano)
Switzerland
Asia Pacific
(简体中文)Matlab中如何批量读取文件夹中的文件进行处理?
[问题点数:40分]
Matlab中如何批量读取文件夹中的文件进行处理?
[问题点数:40分]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
匿名用户不能发表回复!|matlab中text&函数在显示字符串时的使用方法
matlab中text 函数在显示字符串时的使用方法
在当前轴中创建text对象。函数text是创建text图形句柄的低级函数。可用该函数在图形中指定的位置上显示字符串。
text(x,y,'string')在图形中指定的位置(x,y)上显示字符串string
text(x,y,z,'string')
在三维图形空间中的指定位置(x,y,z)上显示字符串string
text(x,y,z,’string’.'PropertyName',PropertyValue…)
对引号中的文字string定位于用坐标轴指定的位置,且对指定的属性进行设置。表7-6给出文字属性名、含义及属性值。
定义字符串
能否对文字进行编辑
有效值:on、off
缺省值:off
Interpretation
TeX字符是否可用
有效值:tex、none
缺省值:tex
字符串(包括TeX字符串)
有效值:可见字符串
放置字符串
text对象的范围(位置与大小)
有效值:[left, bottom, width, height]
HorizontalAlignment
文字水平方向的对齐方式
有效值:left(文本外框左边对齐,缺省对齐方式)、center(文本外框中间对齐)、right(文本外框右边对齐)
缺省值:left
文字范围的位置
有效值:[x,y,z]直角坐标系
缺省值:[](空矩阵)
文字对象的方位角度
有效值:标量(单位为度)
文字范围与位置的单位
有效值:pixels (屏幕上的像素点)、normalized
(把屏幕看成一个长、宽为1的矩形)、inches(英寸)、centimeters(厘米)、points
(图象点)、data
缺省值:data
VerticalAlignment
文字垂直方向的对齐方式
有效值:top
(文本外框顶上对齐)、cap(文本字符顶上对齐)、middle(文本外框中间对齐)、baseline(文本字符底线齐)、bottom(文本外框底线对齐)
缺省值:middle
指定文字字体
设置斜体文字模式
有效值:normal(正常字体)、italic(斜体字)、oblique(斜角字)
缺省值:normal
设置文字字体名称
有效值:用户系统支持的字体名或者字符串FixedWidth。
缺省值为 Helvetica
文字字体大小
有效值:结合字体单位的数值
缺省值为:10 points
设置属性FontSize的单位
有效值:points
(1点=1/72英寸)、normalized(把父对象坐标轴作为一单位长的一个整体;当改变坐标轴的尺寸时,系统会自动改变字体的大小)、inches
(英寸)、Centimeters(厘米)、Pixels(像素)
缺省值:points
FontWeight
设置文字字体的粗细
有效值:light(细字体)、normal(正常字体)、demi(黑体字)、Bold(黑体字)
缺省值:normal
控制文字外观
设置坐标轴中矩形的剪辑模式
有效值:on、off
on:当文本超出坐标轴的矩形时,超出的部分不显示;
off:当文本超出坐标轴的矩形时,超出的部分显示。
缺省值:off
设置显示与擦除文字的模式。这些模式对生成动画系列与改进文字的显示效果很有好处。
有效值:normal、none、 xor、 background
缺省值:normal
SelectionHighlight
设置选中文字是否突出显示
有效值:on、off
缺省值:on
设置文字是否可见
有效值:on、off
缺省值:on
设置文字颜色
有效的颜色值:ColorSpec
控制对文字对象的访问
HandleVisibility
设置文字对象句柄对其他函数是否可见
有效值:on、callback、off
缺省值:on
设置文字对象能否成为当前对象(见图形CurrentObject属性)
有效值:on、off
缺省值:on
文字对象的一般信息
文字对象的子对象(文字对象没有子对象)
有效值:[](即空矩阵)
文字对象的父对象(通常为axes对象)
有效值:axes的句柄
设置文字是否显示出“选中”状态
有效值:on、off
缺省值:off
设置用户指定的标签
有效值:任何字符串
缺省值:’’(即空字符串)
设置图形对象的类型(只读类型)
有效值:字符串’text’
设置用户指定数据
有效值:任何矩阵
缺省值:[](即空矩阵)
控制回调例行执行程序
BusyAction
设置如何处理对文字回调过程中断的句柄
有效值:cancel、queue
缺省值:queue
ButtonDownFcn
设置当鼠标在文字上单击时,程序做出的反应(即执行回调程序)
有效值:字符串
缺省值:' '(空字符串)
设置当文字被创建时,程序做出的反应(即执行的回调程序)
有效值:字符串
缺省值:' '(空字符串)
设置当文字被删除(通过关闭或删除操作)时,程序做出的反应(即执行的回调程序)
有效值:字符串
缺省值:' '(空字符串)
Interruptible
设置回调过程是否可中断
有效值:on、off
缺省值:on(能中断)
UIContextMenu
设置与文字相关的菜单项
有效值:用户相关菜单句柄
MATLAB资源网:
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

我要回帖

更多关于 matlab fontname 宋体 的文章

 

随机推荐