help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: creating a plot of a self-defined function


From: Juan Pablo Carbajal
Subject: Re: creating a plot of a self-defined function
Date: Mon, 17 Feb 2014 13:24:03 +0100

On Mon, Feb 17, 2014 at 1:09 PM, Erik Leunissen <address@hidden> wrote:
> On 02/17/2014 11:35 AM, Juan Pablo Carbajal wrote:
>>
>> On Mon, Feb 17, 2014 at 10:47 AM, Erik Leunissen <address@hidden> wrote:
>>>
>>> function C = myfunc (x, t, M=100.0 , A=1.0, v=1.0, Dx=2.0, k=1.0)
>>>         C=M/A*exp(-(x-v*t)^2/(4*Dx*t)-k*t)/(2*sqrt(pi*Dx*t));
>>> endfunction
>>
>>
>> Ok, the problem is the following: You are asking octave to divide by
>> the matrix t. Since t can't be inverted, octave warns you that the
>> condition number of the inverse ("rcond") is below machine precision
>> (the inverse has a 0 singular value, i.e. not inverted). Ok, but where
>> did you ask for a matrix division?
>> Well, ezmesh internally makes a mesh of the arguments of the functions
>> and then it passes them to your function. If you change your function
>> defintion to
>>
>> function C = myfunc (x, t, M=100.0 , A=1.0, v=1.0, Dx=2.0, k=1.0)
>>   S = Dx*t;
>>   C = M/A * exp ( -(x-v*t).^2 ./ (4*S) - k*t ) ./ (2*sqrt(pi*S) );
>> endfunction
>> You will get no warning and the plot will be produced.
>> Note the "./" and the ".^" opertors. This are element-wise operators.
>> It allows the caller to evaluate on matrix input arguments as if they
>> were a collection of different input pairs.
>>
>
> Thanks very much for your explanation, Juan Pablo (the code does what I
> wanted).
>
> Your answer also touches on something else that I wanted to learn as a next
> step: how to make the function operate on matrices/vectors.
> Thanks for being ahead of that; I'm going to explore that subject further.
>
>
> Erik Leunissen
> --
>
>
>
>> Note that you can achieve the same plot by using meshgrid, i.e.
>> [X Y] = meshgrid (linspace (-5,10,20), linspace (0,10,20) );
>> Z = myfunc (X, Y);
>> mesh (Z)
>>
>
Erik, note that a function of a matrix, like eigs (eigenvalues)
interprets a matrix as input as a single input value, i.e. the matrix
itself. But sometimes we want a user defined function to understand
that a matrix input represents a collection of input values where the
function should be evaluated, this is the "element-wise" case.

For example, you can create a discrete Fourier basis quite easily
(warning:this exploits automatic broadcasting, matlab doesn't do it)
t = linspace (0,2*pi,100).';
f = 1:10;
F = [sin(f.*t) cos(f.*t)];
subplot(2,1,1)
plot(t,F(:,1:10));
subplot(2,1,2)
plot(t,F(:,11:end));

Since the functions "sin" and "cos" interprets the input matrix "f.*t"
as a collection of arguments it evaluates on each entry of the matrix.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]