f

#### varargin (no name list) vs. if (has name list)

Hi

if one uses varargin, like
function varlist2(X,Y,varargin)
one doesn't know what name the varargin really is.

I try:
function varlist2(X,Y)
fprintf('%d \n',X);
if(isequal(X,2))
fprintf('%d \n',Y);
end
end
then
>> varlist2(1)
1
>> varlist2(2)
2
??? Input argument "Y" is undefined.

Error in ==> varlist2 at 4
fprintf('%d \n',Y);

>> varlist2(2,5)
2
5

It works and also has varargin: Y and also have a good name.
Isn't this better?

Mike

 0
sulfateion (366)
8/2/2013 1:59:20 AM
comp.soft-sys.matlab 211265 articles. 25 followers. lunamoonmoon (257) is leader.

3 Replies
668 Views

Similar Articles

[PageSpeed] 2

Your question isn't entirely clear. Do you want to print Y when you have two input arguments or only when X has value 2? For the former this might work:

function varlist2(X,varargin)
narginchk(1,2)
switch nargin
case 1
fprintf('%d \n',X);
case 2
Y = varargin{1};
fprintf('%d \n',X);
fprintf('%d \n',Y);
end
end

For the latter you should be carefull not to try to print Y if only one input argument is given, so something like:

function varlist2(X,varargin)
narginchk(1,2)
fprintf('%d \n',X);
if X==2 & nargin == 2
Y = varargin{1};
fprintf('%d \n',Y);
end
end

 0
8/2/2013 7:21:11 AM
On 8/1/2013 8:59 PM, Mike wrote:
> Hi
>
> if one uses varargin, like
>     function varlist2(X,Y,varargin)
> one doesn't know what name the varargin really is.
>
....

Yes one does--it's "varargin" and is a cell array containing the
remaining actual arguments in the third and subsequent positions in the
calling statement, _if_(and_only_if)_ present.

Your code is in error because it assumes there is a value for Y in all
cases even when it isn't there as well as varargin being empty.

You _MUST_ check the number of arguments actually passed with nargin and
ensure your function never references ones that don't exist in any given
call.

Rightfully, any time you write a function w/ two dummy arguments as
above you should require them both to be present and error if not.  For
quick code one often neglects such niceties but by doing so one gets bad
results as you did...

--


 0
none1568 (7453)
8/2/2013 12:51:47 PM

"Mike" <SulfateIon@gmail.com> wrote in message
> Hi
>
> if one uses varargin, like
>   function varlist2(X,Y,varargin)
> one doesn't know what name the varargin really is.

What name the varargin really is WHERE? In the workspace from which varlist2
is being called? There's no guarantee the values you pass into varlist2 as
the 3rd, 4th, etc. inputs HAVE names in that workspace.

x = 4;
varlist2(1, 2, 3, x, x+1, 6)

3 has no name; it's just 3. The second element of varargin (aka the 4th
input to varlist2) has a name in the caller workspace; its name is x. The
third element of varargin (aka the 5th element to varlist2) also has no
name, since x+1 is an _expression_ not a variable.

> I try:
> function varlist2(X,Y)
> fprintf('%d \n',X);
> if(isequal(X,2))
>    fprintf('%d \n',Y);
> end
> end
> then
>>> varlist2(1)
> 1
>>> varlist2(2)
> 2
> ??? Input argument "Y" is undefined.
>
> Error in ==> varlist2 at 4
>    fprintf('%d \n',Y);
>
>>> varlist2(2,5)
> 2
> 5
>
> It works and also has varargin: Y and also have a good name.
> Isn't this better?

Better than what? Better than this?

function varlist2(X,varargin)
fprintf('%d \n',X);
if(isequal(X,2))
fprintf('%d \n',varargin{1});
end
end

>> varlist2(1)
1
>> varlist2(2)
2
Index exceeds matrix dimensions.

Error in varlist2 (line 4)
fprintf('%d \n',varargin{1});

If the second input argument is truly optional, make sure that your code
handles both the case where it is present and the case where it is not.

function varlist2(X,varargin)
fprintf('%d \n',X);
if(isequal(X,2))
if nargin > 1
fprintf('%d \n',varargin{1});
else
error('VARLIST2 expects to be called with 2 inputs when the first
input is 2.');
end
end
end

>> varlist2(1)
1
>> varlist2(2)
2
Error using varlist2 (line 7)
VARLIST2 expects to be called with 2 inputs when the first input is 2.

>> varlist2(2, 3)
2
3

Sure, it requires more coding. But it's not much more coding, and YOU get to
control the exact information that your user sees, which means you may be
able to give them enough information so that they know what they did that
they shouldn't have or vice versa. In either of the first two cases, a user
(particularly a novice user) may not know exactly how to resolve the
problem. IMO the third case tells the user exactly what they need to do:
call VARLIST2 with 2 inputs if they specify 2 as the first input.
Alternately instead of throwing an ERROR you could use WARNING to tell them
what to do next time and what you're going to do.

function varlist2(X,varargin)
fprintf('%d \n',X);
if(isequal(X,2))
if nargin == 1
warning('Specify two input arguments when you call VARLIST2 with a
first input of 2. Using a default of 0.')
Y = 0;
else
Y = varargin{1};
end
fprintf('%d \n',Y);
end
end

--
Steve Lord
slord@mathworks.com
http://www.mathworks.com


 0
slord (13689)
8/2/2013 2:02:39 PM

Similar Artilces:

List of lists of lists of lists...
I would like to have a list of lists N times deep, and my solution is (in pseudocode): def deep(x): a=[x] return a mylist=[] for N: mylist=deep(mylist) Is there a more elegant way to do it? The maine idea is: from a list having the numbre of steps along N dimensions, generate a list with an item at each possible point. Example 1: N=2 list=[2,3] result=[[1,2],[1,2],[1,2]] Example 2: N=3 list=[3,1,2] result=[[[1,2,3]],[[1,2,3]]] -- Ángel Gutiérrez Rodríguez - agr@fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiat...

list of lists of lists ....
Hi, I have a list of data (type A) my list can includes element of type A or a lists, these list can includes element of type A or a lists, and so on ... is there a simple way to obtain a single list of all the elemets of type A ? thanks yomgui I forgot the most important, I am looking for a non recursive method. thanks yomgui yomgui wrote: > > Hi, > > I have a list of data (type A) > my list can includes element of type A or a lists, > these list can includes element of type A or a lists, and so on ... > > is there a simple way to obtain a single list of all the elemets > of type A ? > > thanks > > yomgui recursion. def get_As(L): res = [] for elem in L: if isinstance(elem, A): res.append(elem) elif isinstance(elem, list): res += get_As(elem) return res i also have a Tree class in my rc: http://home.comcast.net/~faulkner612/programming/python/pythonrc.py yomgui wrote: > Hi, > > I have a list of data (type A) > my list can includes element of type A or a lists, > these list can includes element of type A or a lists, and so on ... > > is there a simple way to obtain a single list of all the elemets > of type A ? > > thanks > > yomgui doh. ok, so, recursion is just functional programming sugar for a loop. def get_As(L): checking = [elem for elem in L if isinstance(elem, list)] # the equivalent of elem in recursion all_As =...

Re: fetching method names from a class, and the parameter list from a methodRe: fetching method names from a class, and the parameter list from a method
>>> import inspect >>> help(inspect) Thanks, I have not seen the func params yet, but the default values are so .... Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** ...

Sort a List, in a List of Lists of Lists
Dear Mathgroup, I have a lsit of Lists of Lists: {{{1,2},{2,1},{1,1}},{{1,1},{1,1},{1,2}},{{2,1},{2,2},{1,2}},{{2,2},{1,2},{2,2}},{{1,1},{2,1},{1,2}},{{1,2},{2,2},{2,2}}} I would like to sort the elements in the lowest level of brackets to give {{{1, 2}, {1, 2}, {1, 1}}, {{1, 1}, {1, 1}, {1, 2}}, {{1, 2}, {2, 2}, {1, 2}}, {{2, 2}, {1, 2}, {2, 2}}, {{1, 1}, {1, 2}, {1, 2}}, {{1, 2}, {2, 2}, {2, 2}}} i.e retaining the same structure with the paired elements in the original order. I can't seem to get the syntax right to do this apart from the obvious {{Sort[{1,...

NAME! and NAME@ versus !NAME and @NAME
Leo Brodie's Forth style guide says: save value of (to stack) @name restore value of !name store into name! fetch from name@ I don't understand when it's appropriate to use @name or !name, and when to use name@ or name!. My research so far: The Standard use the latter a lot: C!, 2! R@, F!, DEFER@, etc. But the former seems to be rare. I found !CSP and !BITS in some traditional Forths. Machine Forth use A!/A@ to access the contents of the A register, and !A/@A to access memory. Any ...

select a name at random from a list of names
I have a text file that has a list of names and I want to select a name at random from this list. I want the names to flash in a screen one after another; then stop at one name at random (the same method is shown to draw a lot in some TV shows) ...

select a name at random from a list of names #2
I have a text file that has a list of names and I want to select a name at random from this list. I want the names to flash in a screen one after another; then stop at one name at random (the same method is shown to draw a lot in some TV shows) "Namo " <namo1983@hotmail.com> wrote in message <ikibog$pv8$1@fred.mathworks.com>... > I have a text file that has a list of names and I want to select a name at random from this list. > > I want the names to flash in a screen one after another; then stop at one name at random (the same method is shown to draw a l...

How to randomly selet a name from a list a of 47 names?
I need to write a code for making a random selection from a list of 47 non number data. I have made a data file listing all the data and am aware of the function textscan. But I am not getting it to work. Also, how do I call for a random data that is in the list? Thanks Message was edited by: Van On Nov 12, 5:29=A0pm, Van <sw_kni...@hotmail.com> wrote: > I need to write a code for making a random selection from a list of 47 no= n number data. > > I have made a data file listing all the data and am aware of the function= textscan. But I am not getting it to work. > &g...

How do you sort a name list and list in random order?
--0-1933634877-1061694222=:6505 Content-Type: text/plain; charset=us-ascii I am trying to write a program in which the users will each enter their names and when all names have been entered, I want to randomly sort this list of names several times and then show the order in which they have beeen sorted. I tried using sort(), but this only sorts the names in the order in which they are entered. Any suggestions? Thanks, Cisco --0-1933634877-1061694222=:6505 Content-Type: text/html; charset=us-ascii <DIV>I am trying to write a program in which the users will each enter their names and w...

Re: Sort a List, in a List of Lists of Lists
On 11/13/10 at 12:59 AM, leigh.pascoe@inserm.fr wrote: >I have a lsit of Lists of Lists: >{{{1,2},{2,1},{1,1}},{{1,1},{1,1},{1,2}},{{2,1},{2,2},{1,2}},{{2,2}, >{1,2},{2,2}},{{1,1},{2,1},{1,2}},{{1,2},{2, 2},{2,2}}} >I would like to sort the elements in the lowest level of brackets to >give >{{{1, 2}, {1, 2}, {1, 1}}, {{1, 1}, {1, 1}, {1, 2}}, {{1, 2}, {2, >2}, {1, 2}}, {{2, 2}, {1, 2}, {2, 2}}, {{1, 1}, {1, 2}, {1, 2}}, >{{1, 2}, {2, 2}, {2, 2}}} >i.e retaining the same structure with the paired elements in the >original order. I can't seem...

Removing file names with '.' in their names from list?
Currently I'm using this code to output a list of files to a .rhtml page: <% Dir.foreach("/") do |file| next if File.fnmatch('*.*', file) puts '<a href="file">' + file + '</a>' end %> This removes files from the list output such as 'photo.jpg'. But it leaves the files with names like '.htaccess', ',' and '..'. I could create more of the 'next' statements explicitly for those file and directory names but wondering if there's a more elegant way to say don't output files with ...

List of Atom or List of List??

Copying a List to a List of Lists
Hi, I am having trouble with the following: I wish to have a list of lists of type Double called A. I then have a separate List of Doubles called B which i wish to add to A. I then want to be able to clear B and reuse it without clearing what I have added to A. Currently my code looks like: for(int i=0;i<seqLength;i++) { B.clear(); for(int j=i+1;j<seqLength;j++) { if(fourGameteTest(i,j)) { B.add(segPositions.get(j)); } } A.get(i).add(B); } However, it seems that due to, I guess the element held in A being a reference to the same pl...

Extracting a List from a List of lists
Hi, I have an ArrayList of ArrayLists. I want to extract all the lists, but I dont know how many ArrayLists will be in the ArrayList. I know I can do it if i know how many lists are there using the ArrayList get() method. this is how i'm doing it List<String> list1 = new ArrayList<String>(); list1 = res.get(0); List<String> list1 = new ArrayList<String>(); list2 = res.get(1); List<String> list1 = new ArrayList<String>(); list3 = res.get(2); But if theres only two lists in the list i get a NullPointerException Is there any way i can loop through the l...

convert list of lists to list
Is there a way to convert list_of_listsA to list_of_listsB, where one list in listof lists A is one element of listB? list_of_listsA: [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], ['koe'], ['arm*', '*', '*(haar)'], ['groei*', '*', '*', '*', '*']] listB: ['klas* * *', 'mooi* * * *, 'koe', 'arm* * * (haar)', 'groei* * * * *'] Thankx! antar2 wrote: > Is there a way to convert list_of_listsA to list_of_listsB, where one >...

How to have a list of lists (or array of lists)
Hi, I want to have many lists, such as list0, list1, list2, ..., each one holding different number of items. Is there something like list[0] list[1] list[2] so that I can iterate through this list of lists? Thanks! bahoo On Apr 3, 7:12 pm, "bahoo" <b83503...@yahoo.com> wrote: > Hi, > > I want to have many lists, such as list0, list1, list2, ..., each one > holding different number of items. > Is there something like > list[0] > list[1] > list[2] > > so that I can iterate through this list of lists? > > Thanks! > bahoo listOfLists = [...

List of a list
Hi, I'm very new to latex. I'm trying to make a list of a list, with: \begin{list}{} \item \begin{list}{} \item \end{list} \end{list} However, I'm getting the error: Runaway argument? ! Paragraph ended before \list was complete. <to be read again> \par l.2273 However, I can do a list of enumerates, but that's not what I want. Is this a clash in syntax? Is there a way to prevent this? Please help. Michael On 1 Nov 2004 00:19:43 -0800, Michael <dayzman@hotmail.com> wrote: > Hi, > I'm very new to latex. I'm trying to make a list ...

List of lists
So you can create listoffigures tableofcontents and listoftables, but can you and if so how do you do the same thing for a list of numbered lists? Cheers Try the tocloft package: http://www.ctan.org/tex-archive/help/Catalogue/entries/tocloft.html On 21 Mar, 17:26, "Matt" <matthew.w.tur...@gmail.com> wrote: > Try the tocloft package: > > http://www.ctan.org/tex-archive/help/Catalogue/entries/tocloft.html That looks great, cheers. But I am having trouble using it. This is the code I am trying, just lifted from the instructions: \newcommand{\listanswername}{List o...

List of lists...
I would like to add a List environment with an accompanying list of lists included at the front of the document. Basically, a List is like a table or a figure. However, I want to be able to refer to a bulleted list. I am using gatech-thesis.cls (which is based on report.cls). I went through report.cls, and copied everything having to do with figures into gatech-thesis.cls (just after it includes report.cls) and changed everything that said figure to list. Then, I went through gatech-thesis.cls, and copied everything having to do with figures, changing everything that said figure to list.....

Given library name and cell name, how to get the list of viewnames
Hi all, In skill I know library name and cell name. How can i get a list of all available viewnames. Thanks, Suresh t_libName = "your_lib" t_cellName = "your_cell" l_cellViews = ddGetObj( t_libName t_cellName )~>views Bernd suresh j wrote: > Hi all, > In skill I know library name and cell name. > How can i get a list of all available viewnames. > Thanks, > Suresh > >>>>> "suresh" == suresh j <suresh> writes: suresh> Hi all, In skill I know library name and cell name. How can suresh> i get...

name list
I have the following input file in the form of a NAMELIST: $ga irestrt=0, microga=1, npopsiz= 5, nparam= 2, pmutate=0.02d0, maxgen=200, idum=-1000, pcross=0.5d0, itourny=1, ielite=1, icreep=0, pcreep=0.04d0, iunifrm=1, iniche=0, nchild=1, iskip= 0, iend= 0, nowrite=1, kountmx=5, parmin= 2*0.0d0, parmax= 2*1.0d0, nposibl=2*32768, nichflg=2*1,$end Parmin, parmax and npossibl are the same for all the components of the array. I would like to change that and allocate different values to the components of the array. The size of the array is...

list*list
There must be a better way to multiply the elements of one list by another: a = [1,2,3] b = [1,2,3] c = [] for i in range(len(a)): c.append(a[i]*b[i]) a = c print a [1, 4, 9] Perhaps a list comprehension or is this better addressed by NumPy? Thanks, jab > There must be a better way to multiply the elements of one list by > another: > > a = [1,2,3] > b = [1,2,3] > c = [] > for i in range(len(a)): > c.append(a[i]*b[i]) > a = c > print a > [1, 4, 9] > > Perhaps a list comprehension or is this better addressed by NumPy? First of all: it's ...

When is a List not a List?
g[x_, n_] := x^n FullForm[Table[g[x, n], {n, 1, 2}]] FullForm[{g[x, 1], g[x, 2]}] Plot[{g[x, 1], g[x, 2]}, {x, 0, 1}, PlotStyle -> {Red, Blue}] Plot[Table[g[x, n], {n, 1, 2}], {x, 0, 1}, PlotStyle -> {Red, Blue}] The FullForm[]s are identical. One Plot[] has red and blue curves; the other has two blue curves. Quirky! AES wrote: > g[x_, n_] := x^n > FullForm[Table[g[x, n], {n, 1, 2}]] > FullForm[{g[x, 1], g[x, 2]}] > Plot[{g[x, 1], g[x, 2]}, {x, 0, 1}, PlotStyle -> {Red, Blue}] > Plot[Table[g[x, n], {n, 1, 2}], {x, 0, 1}, PlotStyle -> {Red, Blue}] > > The FullForm[]s are identical. One Plot[] has red and blue curves; the > other has two blue curves. > > Quirky! Not at all, as it has already been explained many times in this very newsgroup (notwithstanding the online help that contains some examples illustrating this point). Plot does not evaluate immediately its arguments because it has the attribute HoldAll: Attributes[Plot] {HoldAll, Protected} So, having the attribute HoldHold, what Plot "sees" in first instance the unevaluated expression Table[g[x, n], {n, 1, 2}], which stands for only *one* function. Thus the choice of colors is just for one function/expression, not for the list of functions that will be returned after evaluation of the first argument. To force the evaluation of the first argument before doing anythin...

Web resources about - varargin (no name list) vs. if (has name list) - comp.soft-sys.matlab

A Review of the Free Scilab Matrix Language
What you need to know about the Linux port of Scilab, a Mathematics and graphing Language.

MATLAB Documentation - MathWorks Deutschland
MATLAB is a high-level language and interactive environment for numerical computation, visualization, and programming.

GNU Octave: Concept Index
GNU Octave: Concept Index

Resources last updated: 3/8/2016 6:33:23 AM