How can we define a function with variables which are in the for loop and function is also under for loop?

4 次查看(过去 30 天)
I want to define the function as
For i=1:100
fi(x0,x1, x2, ....xi)=x0^2+x1^2+.....xi^2
end
where for loop is on the functions(fi) as well as on the variables.
  4 个评论
Stephen23
Stephen23 2020-9-11
"but I have to write 1000 functions of 1000 variables. what should I do now??"
Use arrays and indexing, then you can solve your task efficiently using MATLAB.
Using 1000 different variables would not be a good use of MATLAB.

请先登录,再进行评论。

回答(2 个)

KSSV
KSSV 2020-9-11
编辑:KSSV 2020-9-11
Read about anonymous function.
EXample:
f = @(x1,x2,x3) 2*x1.^3+3*x2.^2+x3 ;
x1 = rand(10,1) ; x2 = rand(10,1) ; x3 = rand(10,1) ;
val = f(x1,x2,x3)
  3 个评论
KSSV
KSSV 2020-9-11
You are not supposed to have like that...that case, you need to collect them into a matrix and do the below:
f = @(x1,x2,x3) x1.^2+x2.^2+x3.^2 ;
x1 = rand(10,1) ; x2 = rand(10,1) ; x3 = rand(10,1) ;
val = f(x1,x2,x3)
p = sum([x1 x2 x3].^2,2) ; % you need to do this
Steven Lord
Steven Lord 2020-9-11
I recommend not having your function accept 1000 separate input arguments. Write one general function.
f = @(x) sum(x.^2);
Now you can call it with however long a vector you want.
f(1:5)
f(1:10)
f(2:2:8)
If you're using a sufficiently recent release, you could even have f accept arrays.
g = @(x) sum(x.^2, 'all');
g(magic(3))

请先登录,再进行评论。


Ameer Hamza
Ameer Hamza 2020-9-11
If you want to have a variable number of inputs, you can use varargin
f = @(varargin) sum([varargin{:}].^2);
Result
>> f(1,1,5)
ans =
27
>> f(1,1,5,22,32,34,1,2,3,4,5,1,2,3,45,32,23,10)
ans =
6438

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by