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

5 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 11 Sep 2020
"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.

Sign in to comment.

Answers (2)

KSSV
KSSV on 11 Sep 2020
Edited: KSSV on 11 Sep 2020
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 Comments
KSSV
KSSV on 11 Sep 2020
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 on 11 Sep 2020
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))

Sign in to comment.


Ameer Hamza
Ameer Hamza on 11 Sep 2020
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

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!