Calculations with functions in cells
Show older comments
Hello I have the matrix d and I would like to calculate the minimum value in the first cell d{1}. But I have a mistake somewhere:
A1=rand(64,1);
A2=rand(2,2);
for k = 1:1:2
d{k}=@(z) (((A1(:,1)-A2(k,1)).^2)+((z-A2(k,2)).^2));
end
z0=[0,0];
fminsearch(d{1},z0)
8 Comments
Robert U
on 9 Nov 2017
Hello Spyros Polychronopoulos:
f(x) is a function that returns a scalar, and x is a vector or a matrix.
Your function d{k} returns a vector.
Kind regards,
Robert
Spyros Polychronopoulos
on 9 Nov 2017
Hello Spyros Polychronopoulos:
As your examples do not fit your erroneous solution, I suggest to try the following:
Example 1:
A = [2,4,8,16];
for k = 1:numel(A)
C{k}=@(x)(x(k)-A(k)+5).^2;
end
fun = @(x)sum(cellfun(@(f)f(x),C));
fun([0,0,0,0])
Result 1:
>> ans = 140
Example 2:
A1=[5,8];
fun = @(x) sum((x-A1).^2);
x0 = [-1.2,1];
fun(x0)
Result 2:
>> ans = 87.4400
Example 3:
A1=rand(64,1);
A2=rand(2,2);
for k = 1:1:2
d{k}=@(z) (((A1(:,1)-A2(k,1)).^2)+((z-A2(k,2)).^2));
end
d{2}(0)
Result 3:
>> ans = 0.5247
0.3243
0.3132
...
0.4571
As you can see (and should have seen from own trials) the first two examples output scalars whereas the third example gives a vector which is not supported by fminsearch().
Kind regards,
Robert
Spyros Polychronopoulos
on 13 Nov 2017
Stephen23
on 13 Nov 2017
"... I am looking to find a number of solutions for in-depended values that's why I was trying to have z1,z2,...,zn variables... But I tried the below to get z1,z2,...,z64."
Ugh, what a slow, complex, and buggy way to store data and write code.
"Then adding them up (doesn't work with sum or plus)"
Yep, that is true. And this is one of many reasons that all MATLAB experts will advise you to avoid magically creating or accessing lots of separate variables. The MATLAB documentation specifically warns against doing what you are trying to do: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Once beginners learn to avoid using lots of numbered variables or magically trying to access variable names dynamically then their code will be simpler, neater, faster, more efficient, less buggy, and easier to debug. Read this to know more:
Spyros Polychronopoulos
on 13 Nov 2017
Juliana Tavora
on 5 May 2018
Hi Spyros Polychronopoulos, did you find a solution for your question? I am having a similar problem.
I have 2 arrays (200x200 each) and trying to make a sum of functions.
Spyros Polychronopoulos
on 5 May 2018
Answers (0)
Categories
Find more on Image Arithmetic 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!