help-octave
[Top][All Lists]

## Re: Constants in functions?

 From: Kai Torben Ohlhus Subject: Re: Constants in functions? Date: Fri, 6 Mar 2020 11:19:53 +0900 User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.5.0

```On 3/6/20 3:36 AM, Sergei Steshenko via Help list for GNU Octave wrote:
>
> On 05/03/2020 20:12, Windhorn, Allen E [ACIM/LSA/MKT] wrote:
>> What's the accepted way to define a constant inside a function?  Example:
>> ____________________________________
>> function [sc, err] = symmcomp(abc)
>>    % Function accepts [abc] complex components and delivers symmetrical
>>    % components as a vector [x0, x1, x2] of complex values
>>    persistent a = complex(-0.5, sqrt(3)/2);    % Rotation vector
>>    %
>>    % Build conversion matrix_type (constant)
>>    persistent A = [1, 1, 1;
>>            1, a, a^2;
>>            1, a^2, a]./3;
>>    %
>>    % Make abc a column vector
>>    if (length(abc)>3)
>>      sc = [];
>>      err = "Too many components!";
>>    elseif (length(abc)<3)
>>      sc = [];
>>      err = "Too few components!";
>>    else
>>      abc = reshape(abc,[3,1]);
>>      sc = A*abc;
>>      err = "";
>>    endif
>> endfunction
>> ________________________________________
>>
>> Here a is a constant and A is a constant matrix.  I used persistent in
>> hopes
>> it would prevent them from being redefined every time the function is
>> called.
>> In C++ I would use the "const" keyword.
>>
>> Regards,
>> Allen
>
>
> An ugly (because IIRC Octave doesn't have nested functions) way:
>
> function retval = TWO()
>
>   retval = 2;
>
> endfunction
>
> .
>
> The above function will return 2. You can similarly return matrix, row o
> column vector, etc.
>
>
> --Sergei.
>

Dear Allen,

Your code seems fine to me.  Using "persistent" [1] avoids the variables
to be redefined each time the function is invoked.  And if you do not
change it's value, it is "constant".  So what it is exactly you are

Do you fear the value to be changed accidentally (by whom)?  How should
this happen, when you write the function?  In that case you can create a
subfunction [2], as suggested by Sergei, plus defining "retval" as
"persistent" for performance reasons (the variable "retval" would be
recreated in each function call).  I do not see a benefit of
nested-functions [3] in this scenario.

Neither Octave nor Matlab have a concept of C++ "const" variables.  Only
within classdef classes you can define constant properties [4].  But the

HTH,
Kai

[1] https://octave.org/doc/v5.2.0/Persistent-Variables.html
[2] https://octave.org/doc/v5.2.0/Subfunctions.html
[3] https://octave.org/doc/v5.2.0/Nested-Functions.html
[4] https://octave.org/doc/v5.2.0/Properties.html

```