フィルターのクリア

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 Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by