[Fittype using an anonymous function] Can the independet variables be indices for an array?
4 views (last 30 days)
Show older comments
Is there a way to use the independent variables as indices for an array?
For example, in the following example, 'shape' is a 2D array, and x and y are used as indices, e.g., shape(x,y).
ft = fittype(@(nB,h,shape,lambda,nA,x,y) ...
2*pi/lambda*abs(nA-nB)*shape(x,y)*h, ...
'dependent','z','independent',{'x','y'},...
'problem',{'shape','lambda','nA'},'coefficients',{'nB','h'});
I get the following error:
Error using fittype>iAssertIsMember (line 1084)
Problem parameter shape does not appear in the equation expression.
I tried to define another function to access the array.
getElementOf = @(array,ii,jj) array(ii,jj);
ft = fittype(@(nB,h,shape,lambda,nA,x,y) ...
2*pi/lambda*abs(nA-nB)*getElementOf(shape,x,y)*h, ...
'dependent','z','independent',{'x','y'},...
'problem',{'shape','lambda','nA'},'coefficients',{'nB','h'});
When defining the equation '2*pi/lambda*abs(nA-nB)*getElementOf(shape,x,y)*h' in a separate anonymous function, I get a correct result; however, its use in the fittype definition produces an error:
Error using fittype/testCustomModelEvaluation (line 12)
Expression 2*pi/lambda*abs(nA-nB)*getElementOf(shape,x,y)*h is not a valid MATLAB expression, has non-scalar
coefficients, or cannot be evaluated:
Error while trying to evaluate FITTYPE function :
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Thanks.
2 Comments
Answers (1)
Shubham
on 3 May 2023
Hi Imaging3D,
It is very well possible to use independent variables as indices for an array. But it seems in your code, the issue is not related to using independent variables as indices.
The error message suggests that the problem parameter 'shape' is not appearing in the equation expression. This means that 'shape' is not being passed correctly to the fittype function.
Make sure that the 'shape' variable is defined and passed correctly to the fittype function. You can also try removing the 'problem' parameter and passing the 'shape' variable as an independent variable, like this:
ft = fittype(@(nB,h,lambda,nA,x,y,shape) ...
2*pi/lambda*abs(nA-nB)*shape(x,y)*h, ...
'dependent','z','independent',{'x','y','shape'},...
'coefficients',{'nB','h'});
This should allow you to use 'shape' as an independent variable and access its elements using 'x' and 'y' as indices.
0 Comments
See Also
Categories
Find more on Linear and Nonlinear Regression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!