acer

32313 Reputation

29 Badges

19 years, 311 days
Ontario, Canada

Social Networks and Content at Maplesoft.com

MaplePrimes Activity


These are answers submitted by acer

Have a look here.

This brings up an interesting point. The Online Help is for the current release (which is Maple 13 at the time I write this). It would be useful if each help-page included a note as to the release in which the page was introduced or became relevant. Even if that could not be done comprehensively for all existing pages, it might still be useful were it done for all pages added since, say, Maple 12.

acer

Replace printf below with a call to fprintf (with a file name as the new first argument). That will make it print to a file rather than to the Maple interface.

> listA:=[40,50,60]:
> listB:=[80,100]:
> values:=[[1,2],[4,5],[6,7]]:

> for i from 1 to nops(listA) do
>   for j from 1 to nops(listB) do
>      printf("name_%d_%d = %d\n", listA[i],listB[j],values[i,j]);
>   end do:
> end do:

name_40_80 = 1
name_40_100 = 2
name_50_80 = 4
name_50_100 = 5
name_60_80 = 6
name_60_100 = 7

If values[i,j] are floating-point then you might use %g or %e or %f rather than %d. See the fprintf help-page for descriptions of the various formats.

acer

Presumably you are supposed to implement the elementwise parts of that task, otherwise you could write the absurdly trivial procedure,

inv2x2 := (A::Matrix(2,2)) -> A^(-1):

One way to get the formula for this is to find the inverse of a "general" 2x2 Matrix. By "general" I mean that every element has its own unique and mathematically unrelated name.

> M := Matrix(2,2,symbol=m);
                                [m[1, 1]    m[1, 2]]
                           M := [                  ]
                                [m[2, 1]    m[2, 2]]
 

So just issue the command M^(-1) and implement inside your precdure the formulae you see for each entry of the result .

Look for a common expression as the denominator of each entry, and have your procedure compute that first. Ask youself, what should your procedure do if that denominator is zero?

This may not always be the best way to go about such problems, but in this case it works easily.

acer

> Eq := cT*a*b*sT+cT*c+sT*d+cT*sT;
                     Eq := cT a b sT + cT c + sT d + cT sT
 
> algsubs(cT*sT=s2T, Eq);
                          cT c + sT d + a b s2T + s2T

The help-page for subs shows a few algsubs examples, and has a link to the algsubs help-page in its See Also section.

acer

I hope that there is an easier way than this (presuming that I haven't done it all wrong). It'd be easy if one could simply subtract from the original sample values. But you mentioned that you wanted those states as the immediate output (from Sample).

> MyProbTable := proc(plist::list)
>   module()
>   export Conditions, ParentName, Parameters, CDF, Mean,
>          ProbabilityFunction, RandomSample, RandomVariate;
>   options Distribution, Discrete;
>   Conditions := [plist::('list(realcons)')];
>   ParentName := ':-ProbabilityTable';
>   Parameters := [plist];
>   CDF := t -> sum(plist['k'+1],('k') = 0 .. min(floor(t),nops(plist)-1));
>   ProbabilityFunction := t -> piecewise(t < 0,0,t+1 <= nops(plist),plist[floor(t)+1],0);
>   Mean := sum((i-1)*plist[i],i = 1 .. nops(plist));
>   RandomSample := proc(n::posint) local pr, oldopmod;
>     oldopmod := kernelopts(opaquemodules);
>     kernelopts(opaquemodules=false);
>     try
>       Statistics:-ExternalSupport:-Initialize();
>       pr := Statistics:-ExternalSupport:-DefineExternal("MapleAliasUrnSample");
>     catch:
>       error;
>     finally
>       kernelopts(opaquemodules=oldopmod);
>     end try;
>     pr(n,Array([op(plist)],('datatype') = float[8]));
>   end proc;
>   RandomVariate := proc() local pr, oldopmod;
>     oldopmod := kernelopts(opaquemodules);
>     kernelopts(opaquemodules=false);
>     try
>       Statistics:-ExternalSupport:-Initialize();
>       pr := Statistics:-ExternalSupport:-DefineExternal("MapleAliasUrnSample");
>     catch:
>       error;
>     finally
>       kernelopts(opaquemodules=oldopmod);
>     end try;
>     pr(1,Array([op(plist)],('datatype') = float[8]));
>   end proc;
> end module:
> end proc:

> with(Statistics):

> P := [1/2,1/8,3/8]:

> X := RandomVariable(MyProbTable(P)):

> Sample(X,20);
          [2, 2, 2, 0, 2, 2, 0, 2, 0, 0, 2, 1, 0, 0, 1, 0, 2, 0, 2, 0]
 
> Mean(X), evalf(Mean(X)), evalf(Mean(Sample(X,1000000)));
                        7/8, 0.8750000000, 0.8748580000

> CDF(X,-1), CDF(X,0), CDF(X,1), CDF(X,2), CDF(X,3);
                               0, 1/2, 5/8, 1, 1

This trick doesn't extend to the situation where your values instead are, say, -3, -2, and -1. I'd be tempted to suspect that there must be an easier way, except that Statistics is not so strong for customized discrete distributions.

acer

You may have typo'd in the fourth list, which you gave as [4,5,5,7]. If so, then it doesn't affect the method below. If you didn't, then it's not clear whether you wanted to transpose the data (have a look at Matrix(L)).

> L := [[1,2,3,4],[2,3,5,5],[3,4,4,6],[4,5,5,7]]:
 
> sort(L,(a,b)->a[3]<b[3]);
           [[1, 2, 3, 4], [3, 4, 4, 6], [4, 5, 5, 7], [2, 3, 5, 5]]
> sort(L,(a,b)->a[4]<b[4]);
           [[1, 2, 3, 4], [2, 3, 5, 5], [3, 4, 4, 6], [4, 5, 5, 7]]
 
> S:=(l,n)->sort(l,(a,b)->a[n]<b[n]):

> S(L,3);
           [[1, 2, 3, 4], [3, 4, 4, 6], [4, 5, 5, 7], [2, 3, 5, 5]]
 
> S(L,4);
           [[1, 2, 3, 4], [2, 3, 5, 5], [3, 4, 4, 6], [4, 5, 5, 7]]

> L := [[1,2,3,4],[2,3,5,5],[3,4,4,6],[4,5,6,7]]:
> S(L,3);
           [[1, 2, 3, 4], [3, 4, 4, 6], [2, 3, 5, 5], [4, 5, 6, 7]]
 
> S(L,4);
           [[1, 2, 3, 4], [2, 3, 5, 5], [3, 4, 4, 6], [4, 5, 6, 7]]

acer

> expr := (1+1/(n+1))^(n+1)-(1+1/n)^n:

> fsol:=fsolve(abs(expr)=10^(-5),n=0..1000);
                              fsol := 367.2490976
 
> isol:=trunc(fsol);
                                  isol := 367
 
> is( eval(abs(expr)<10^(-5),n=isol) );
                                     false
 
> isol:=trunc(fsol)+1;
                                  isol := 368
 
> is( eval(abs(expr)<10^(-5),n=isol) );
                                     true
 
> fsol:=fsolve(abs(expr)=10^(-5),n=-1000..0);
                             fsol := -370.0824305
 
> isol:=trunc(fsol);
                                 isol := -370
 
> is( eval(abs(expr)<10^(-5),n=isol) );
                                     false
 
> isol:=trunc(fsol)-1;
                                 isol := -371
 
> is( eval(abs(expr)<10^(-5),n=isol) );
                                     true

acer

intVec := [1,2,3,4,5]:

myGraphs := proc(intvec, fname)
  local myplot;
  myplot[1] := Statistics:-PieChart(intvec,'color'='red'..'yellow');
  myplot[2] := plots:-textplot([1,2,"some stuff"]);
  plotsetup('postscript','plotoutput'= cat(fname,".ps"),
            'plotoptions'="colour=cmyk,noborder");
  print(plots:-display(myplot[1],myplot[2]));
  plotsetup('default');
  return NULL;
end proc:

myGraphs(intVec, foo);

plot(sin(x));

acer

The concept "package" may mean different things to different people. But for now I will suppose that you mean that you have a procedure or several procedures, possibly with or without accompanying help-pages and example worksheets, which you wish to save and re-use. By saving them, you hope to either re-use them yourself in other Maple sessions, or to allow colleagues to use them in Maple sessions on their own machines.

Maple reads procedures from archives with the .mla filename suffix. Maple searches for .mla archives by looking in directories (OS folders) in the order that they appear in the Maple libname variable's value. See the ?libname help-page for more.

You can create such archives, and save to them, using the routines in the LibraryTools package. See the ?LibraryTools help-page for details.

One you have saved a procedure inside a .mla archive, then in any new Maple session you can access (use) that procedure as long as the .mla is in a directory or folder in libname. But in any Maple session, you can append to libname. So, rather than having to place the .mla in a certain specified location, you could also simply change your libname to include whatever location the .mla file has.

Here is a very simple example, which creates foo.mla in whatever folder is returned in Maple by command kernelopts(homedir). You don't have to use that folder, of course.

> restart:

> libname := libname,kernelopts(homedir):

> LibraryTools:-Create("foo.mla");

> p := proc(x) sin(x) end proc:

> LibraryTools:-Save(p,foo);

> restart: # a new session!

> p(17); # p is not found in default libname path
                                     p(17)
 
> libname := libname,kernelopts(homedir):

> p(17);
                                    sin(17)

You can either save all your procedures individually to the same .mla archive, or bundle them up first as a Maple module (with option package). See the ?module help-page. This is not a necessary aspect of redistributing or re-using your materials, but it can make things look more organized if you intend to redistrubute your work. There are some other advantages to modules, but those are more advanced.

There is a similar set up for customized help-files. You can write a .mw worksheet which shows how to use a procedure. You can then save that to a .hdb help database archive using the INTERFACE_HELP command. See the ?INTERFACE_HELP help-page for more details. Maple finds and searches .hdb archives in the same way as .mla archives, using the directories in libname. So you can simply place any .hdb file alongside your .mla file so that they get found and used together.

There is also a way to pack up .mla, .hdb, example worksheets, code source text files, and any other file, into an automatically self-unpacking object which Maple can open. There are also some special locations which Maple will search (under your own home directory) even without libname having to be set. I should probably wait until I can write that all out clearly.

It would be better if I rewrote all these note and placed them in the mapleprimes books section, as I've been meaning to do for some time now.

acer

Frequency can mean cycles/unit-of-time, or revolutions/unit-of-time, or 1/unit-of-tme. The second is a common unit of time.

So, using 2*Pi radians as one cycle or revolution

f1,f2 := 1, 1/3: # frequencies, as cycles/second

plot([sin(f1*t*2*Pi),sin(f2*t*2*Pi)],t=0..3);

The above shows two sin plots. One does 1 cycle (2*Pi radians) for every whole unit of t, and the other does 1/3 cycles. You can interpret a unit of t as being a second, for example. The plots are thus done over 3 seconds. One curve does three full cycles and the other shows just one cycle.

You can use the legend or labels options of plot to illustrate it. For example,

f1,f2 := 1, 1/3: # frequencies, as cycles/second

plot([sin(f1*t*2*Pi),sin(f2*t*2*Pi)],t=0..3,
     labels=[typeset(Unit(s)),cycle],
     legend=[typeset(f1*Unit(Hz)),typeset(f2*Unit(Hz))]);

acer

Remain calm. Please put your seat-back into its upright position. Please extinguish all cigarettes.

Seriously, we may be able to give some help. But you are right, posting your code would help. You can use the green up-arrow in the toolbar at the top of this forum's editor (to upload files and worksheets). Or you can put the code inlined right into a post/response here (toggle to Source, and use the <pre> and </pre> tags say).

For the most part in straight Matlab computations will be done in hardware double- precision. There are ways to get around that in (most of) Maple, but it is not the default. There are also ways to use even higher precision in Maple (by setting its Digits environment variable for example), which is generally not possible in Matlab (without having to recourse to its symbolic toolbox).

Let us know what commands you are using, or post or upload the code itself, and it may be possible to offer more precise suggestions.

You may wish to read the ?Digits, ?evalhf, and ?Matrix help-pages.

acer

I can't tell exactly what you want.

> eqn := a*b*c = sqrt(a+2)*d*e:

> sol := isolate(eqn,a);
                                      2  2      2  2 1/2
                             (d e + (d  e  + 8 b  c )   ) d e
                  sol := a = --------------------------------
                                            2  2
                                         2 b  c

> printf("%a == %a\n",lhs(sol),rhs(sol));
a == 1/2/b^2/c^2*(d*e+(d^2*e^2+8*b^2*c^2)^(1/2))*d*e

> solve(eqn,{a});
              2  2      2  2 1/2
     (d e + (d  e  + 8 b  c )   ) d e
{a = --------------------------------},
                    2  2
                 2 b  c

                     2  2      2  2 1/2
           (-d e + (d  e  + 8 b  c )   ) d e
    {a = - ---------------------------------}
                           2  2
                        2 b  c

acer

In Maple, the quotation mark " is used to delimit strings. The single-left-quote is used to delimit names. (One can convert from one to the other, as shown below.) It's not entirely clear to me which you want.

> N := `i love going to the movies`;
                        N := i love going to the movies

> S1 := convert(N,string);
                      S1 := "i love going to the movies"

> S2 := "i love going to the movies"; # same as S1
                      S2 := "i love going to the movies"

> StringTools:-LengthSplit(S2,2);
 "i ", "lo", "ve", " g", "oi", "ng", " t", "o ", "th", "e ", "mo", "vi", "es"

> map(`[]`@parse,[%]);
   [[i], [lo], [ve], [g], [oi], [ng], [t], [o], [th], [e], [mo], [vi], [es]]

note. LengthSplit also works directly on the name N,

> StringTools:-LengthSplit(N,2);
 "i ", "lo", "ve", " g", "oi", "ng", " t", "o ", "th", "e ", "mo", "vi", "es"

map(`[]`,[StringTools:-LengthSplit(N, 2)]);
[["i "], ["lo"], ["ve"], [" g"], ["oi"], ["ng"], [" t"], ["o "], ["th"],

    ["e "], ["mo"], ["vi"], ["es"]]

Notice this difference in converting from strings to names.

> parse(" g");
                                       g

> lprint(%);
g
> convert(" g",name);
                                       g

> lprint(%);
` g`

> map(t->[convert(t,name)],[StringTools:-LengthSplit(N, 2)]);
[[i ], [lo], [ve], [ g], [oi], [ng], [ t], [o ], [th], [e ], [mo], [vi], [es]]

> lprint(%[4]);
[` g`]

acer

The Optimization routines do floating-point calculation, ie. they are not exact. So the issue is whether the result is "close enough" to zero at the current working precision (or with the tolerance used by the routine in question).

The assume=nonnegative option is a convenient way to supply additional constraints on all the variables. It's equivalent to passing such additional constraints as x[1]>=0, x[2]>=0, etc. So, what you are seeing is a constraint violation.

By default,  Optimization routines work at floating-point double precision. Notice that value for y[2] is close to zero (effectively zero) in the double-precision sense.

> evalhf(DBL_EPSILON);
                                                 -15
                          0.222044604925031308 10

Here are two ways to deal with this issue. The first is to apply `fnormal` to the result. See the ?fnormal help-page for an explanation.

> sol := Optimization[NLPSolve](F1, {constraint1, constraint2 },
>   x[2]=x[1]+0.0001..xmax, y[2]=ymin..y[1]-0.0001,
>   assume=nonnegative, maximize);
sol := [0.938888888888889328,
                                                                -15
    [x[2] = 6.33333333333333393, y[2] = -0.165123990869542325 10   ]]

> fnormal(sol);
               [0.9388888889, [x[2] = 6.333333333, y[2] = -0.]]

> fnormal(sol,14);
           [0.93888888888889, [x[2] = 6.3333333333333, y[2] = -0.]]

> fnormal(sol,15,1e-15);
          [0.938888888888889, [x[2] = 6.33333333333333, y[2] = -0.]]

Alternatively, you can obtain results with an even tighter bound on any violation of the constraints.

> Digits:=17:

> sol := Optimization[NLPSolve](F1, {constraint1, constraint2 },
>   x[2]=x[1]+0.0001..xmax, y[2]=ymin..y[1]-0.0001,
>   assume=nonnegative, maximize, feasibilitytolerance=1e-16);
     sol := [0.93888888888888898, [x[2] = 6.3333333333333334, y[2] = 0.]]

See the ?Optimization,options help-page for more explanation of the feasibilitytolerance option.

The waters are a little muddy here, because the Optimization routines respect both the Digits and UseHardwareFloats environment flags. But hopefully the above is enough.

acer

I'm not sure that I understand what you mean by simultaneously, here.

Can you phrase the multi-objective optimization goal in more explicit terms? Is it the case that you have no satisfactory (single) objective function that unifies both U and u (with  some penalty function applied to each)?

For example, can you state the goal in terms of Pareto optimality? If not, then how should the u and U be compared? (Ie. how does a penalty for one relate to a penatly to the other, quantitatively?)

acer

First 299 300 301 302 303 304 305 Last Page 301 of 336