MATLAB: Is there a faster way than repeating this calculation manually

repetition

I have a function file with 6 equations and 6 unknowns:
function F = TEST6lijn300(x)
F = [(x(1)^2 + x(2)^2 -753233.1);
((1447.5-x(3))^2 + (876.3-x(4))^2-966977.2);
((-72.4-x(5))^2 + (1723.1-x(6))^2-957129.6);
(x(5)^2 - 2*(x(5)*x(1)) + x(1)^2 + x(6)^2 - 2*(x(6)*x(2)) + x(2)^2 - 20449);
(x(3)^2 - 2*(x(3)*x(1)) + x(1)^2 + x(4)^2 - 2*(x(4)*x(2)) + x(2)^2 - 20449);
(x(3)^2 - 2*(x(3)*x(5)) + x(5)^2 + x(4)^2 - 2*(x(4)*x(6)) + x(6)^2 - 20449)];
end
I have managed to solve it using:
x0 = [5; 10; 5; 10; 5; 10]; % Make a starting guess at the solution options=optimset('Display','iter','MaxFunEvals',1000); % Option to display output [x,fval] = fsolve(@TEST6lijn300,x0,options) % Call solver
However I need to do this calculation hundreds of times, only changing the numbers 753233.1, 966977.2, and 957129.6. I have hundreds of sets of these three numbers which need to be pasted into the function file. So far, I have been doing it manually, but there must be a better way..

Best Answer

function F = TEST6lijn300(x, p)
F = [(x(1)^2 + x(2)^2 - p(1));
((1447.5-x(3))^2 + (876.3-x(4))^2-p(2));
((-72.4-x(5))^2 + (1723.1-x(6))^2-p(3));
(x(5)^2 - 2*(x(5)*x(1)) + x(1)^2 + x(6)^2 - 2*(x(6)*x(2)) + x(2)^2 - 20449);
(x(3)^2 - 2*(x(3)*x(1)) + x(1)^2 + x(4)^2 - 2*(x(4)*x(2)) + x(2)^2 - 20449);
(x(3)^2 - 2*(x(3)*x(5)) + x(5)^2 + x(4)^2 - 2*(x(4)*x(6)) + x(6)^2 - 20449)];
end
The call would be
...
p = [753233.1, 966977.2, 957129.6] ;
[x,fval] = fsolve(@(x)TEST6lijn300(x,p),x0,options) ;
EDIT2: if all your sets of p values are in an Excel file, you can do the following (that you could make more concise by eliminating temporary variables):
x0 = ...
options = ...
filename = 'myFile.xlsx' ;
sheet = 'mySheet' ;
P = xlsread(filename, sheet) ; % Assuming that there is no numerical
% header in your spreadsheet.
n = size(P, 1) ; % Number of rows (sets of p values).
X = zeros(n, length(x0)) ; % Prealloc for storing x's.
for ii = 1 : n
fh = @(x) TEST6lijn300(x, P(ii,:)) ; % See note below.
X(ii,:) = fsolve(fh, x0, options) ;
end
Note: fh is a function handle on an anonymous function that takes 1 input parameter, x, and calls your function TEST6lijn300 with the two arguments that it requires, here x and ii-th row of P that is the ii-th set of p values. Jan's comment refers to a post explaining that using an anonymous function is the proper way to manage this type of situations where you have to match interfaces between your function and some solver requirements.
Cedric