how to declare parameter data type in a function?

46 views (last 30 days)
Hi.
Recently I want to define a function for non-linear fit and the function is like this
calcfunc=@(A,x)(A(1)./(A(2)+x)+A(3)) ; A0=ones(1,3); A=nlinfit(x,y,calcfunc,A0);
My goal is to calculate A with the given xs and ys. The problem is, I want to declare A(2) to be an integer so as to nlinfit will only take integers into consideration for A(2) while applying a non-linear fit.
How to?

Answers (2)

Ced
Ced on 22 Mar 2016
Edited: Ced on 22 Mar 2016
Hi
Short answer: cast with e.g. int8
Longer answer:
As you probably know, Matlab is quite relaxed when it comes to data types.
Nonetheless, it is possible, but you have to be a bit careful, as the following examples will show:
% 1. declare a as int8 and set a to 2.3
a = zeros(1,'int8');
a = 2.3
>> 2.3
% 2. declare a as int8 and set the value of it's element to 2.3
a = zeros(1,'int8');
a(1) = 2.3
>> 2
% 3. cast any number to int <-- this is what you will probably need
a = int8(2.3)
>> 2
I used an 8 bit integer as an example, but you can select any type you want. The difference between example 1 and 2 is that in example 1, the whole array of a (which is an int8) is replaced by a new array of type double, whereas in example 2, the element (1,1) of array a (which is still int) gets assigned the number 2.3, which is thus cast.

Walter Roberson
Walter Roberson on 22 Mar 2016
It is not possible to mix data types in a numeric array.
If the goal is to have A(2) be an integer datatype so that you get the different semantics of working with integer datatypes, then cast the reference to the appropriate datatype, like int16(A(2)). You have to be pretty careful about working with integer datatypes, they lead to unexpected results and you do not play well with others.
If the goal is to report an error if the handle is invoked and A(2) is not integer valued, then unfortunately at the moment I cannot think of a way to do that without writing at least one additional routine. There is no built in way to turn on type checking for the arguments of function handles, especially not for only one member of a vector that is an argument. There are tests that can be done like isinteger() that are expressions but the error-invoking is error() and assert(), neither of which can be used in expression form (they do not return values) so you cannot code, for example,
assert(A(2)==fix(A(2),'bad trip') + some value
It would not be difficult to code an expression form of assert() but it does not exist and cannot be coded as an anonymous function.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!