Calculate f for multiple inputs
Show older comments
I want to calculate the function f for multiple inputs and then find the number of local and global minima.
% Import the excel data into MATLAB
T = readtable('Task1.xlsx','Range','A7:F106');
% Calculate the function f and find the number of local and global minima
q = T(1:99,4);
x = T(1:99,2);
y = T(1:99,3);
cost = T(1:99,6);
u = [0:100];
v = [0:100];
for i = 1:100
f = sum(q(i)*((u-x).^2) + ((v-y).^2))
end
Answers (1)
Tejas
on 22 Aug 2024
Hello Arashdeep,
The vectors ‘q’, ‘x’, and ‘y’ have dimensions of [99,1], while ‘u’ and ‘v’ have dimensions of [1,101]. Subtracting ‘u’ from ‘x’ and ‘v’ from ‘y’ will cause an error because their dimensions do not match. Additionally, since the vector ‘q’ is [99,1], when the value of ‘i’ reaches 100, an index out of bounds error will occur. To fix this, all the vectors need to be adjusted to have the same dimensions.
Assuming all the vectors are adjusted to a dimension of [100,1], the following steps can be followed:
- To find multiple values of function ‘f’, first step is to pre-allocate memory in which those values can be stored in.
f_values = zeros(100, 1);
uMinusx = u-x;
vMinusy = v-y;
for i = 1:100
f_values(i) = sum(q(i) * (uMinusx.^2 + vMinusy.^2));
end
- Utilize the ‘islocalmin’ function to identify all the local minima. For more information on the ‘islocalmin’ function, refer to this documentation: https://www.mathworks.com/help/matlab/ref/islocalmin.html .
localMinima = islocalmin(f_values);
numLocalMinima = sum(localMinima);
- Use ‘min’ function, to find value and index of function ‘f’ at global minima. Refer to this documentation for more information on ‘min’ function: https://www.mathworks.com/help/matlab/ref/min.html .
[minValue, minIndex] = min(f_values);
Categories
Find more on Transaction Cost Analysis 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!