Effacer les filtres
Effacer les filtres

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

4 vues (au cours des 30 derniers jours)
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 commentaires
Stephen23
Stephen23 le 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.

Connectez-vous pour commenter.

Réponses (2)

KSSV
KSSV le 11 Sep 2020
Modifié(e) : KSSV le 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 commentaires
KSSV
KSSV le 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 le 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))

Connectez-vous pour commenter.


Ameer Hamza
Ameer Hamza le 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

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by