input vector as point to numeric function
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
So I have this function where I pass a multi-variable function, for example lets regards f(x,y) = x^2+y^2.
Inside the function I do not know in advance how many variables will be (I get that number with nargin)
I am trying to get a random point, considef p = rand(1,2) and then get f(p).
Is there a way to generate random points and then get f(p) for multivariable functions?
Most stuff I have seen here is to do save two vectors as x =[....] , y=[...] and then calculate f(x,y), how can I handle this when my function is n-variable because I cant make n vectors of size 1 just to get a point
Thank you
0 commentaires
Réponses (1)
Matt J
le 30 Déc 2021
Modifié(e) : Matt J
le 30 Déc 2021
It's not clear from your description where the random generation of p is supposed to happen. If it happens prior to calling f(), then the natural thing would be to not split p up into separate arguments. Just define f() to take a single, vector argument:
p=rand(1,n);
f=@(p) norm(p).^2
2 commentaires
Matt J
le 31 Déc 2021
now the problem is I cant find the gradients of such function nor knowing how many variable it got using the nargin(f) method..
Extending my example above,
p=rand(1,n);
function [value,gradient] = f(p)
N=numel(p); %number of elements
value=norm(p)^2/N;
gradient=(2/N)*p;
end
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!