input vector as point to numeric function

2 vues (au cours des 30 derniers jours)
Elad Goldenberg
Elad Goldenberg le 30 Déc 2021
Commenté : Matt J le 31 Déc 2021
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

Réponses (1)

Matt J
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
Elad Goldenberg
Elad Goldenberg le 31 Déc 2021
thank you for the answer but this isn't the answer for me :/
I'll explain more, I make a function that gets a multi variable convex function. it can be f(x,y) = x^2+y^2
it can be f(x,y) = x^3-y^10 and also f(x,y,z,t,s)= x +y +z +t +s and etc. inside the function I'm calculating the gradient and then I want to generate points and evaluate them.
I searched and found that if I send the function f = @(x)x(1)^2+x(2)^2+...+x(n)^2 then I can take a vector [1,2,...,n] and use it as a point and calculate f([1,2,...,n]) now the problem is I cant find the gradients of such function nor knowing how many variable it got using the nargin(f) method..
I don't know if this is the correct way of handling this
Matt J
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by