input vector as point to numeric function

2 次查看(过去 30 天)
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

回答(1 个)

Matt J
Matt J 2021-12-30
编辑:Matt J 2021-12-30
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 个评论
Elad Goldenberg
Elad Goldenberg 2021-12-31
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 2021-12-31
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by