input vector as point to numeric function

조회 수: 2 (최근 30일)
Elad Goldenberg
Elad Goldenberg 2021년 12월 30일
댓글: Matt J 2021년 12월 31일
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