How can we define a function with variables which are in the for loop and function is also under for loop?
조회 수: 2 (최근 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
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
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
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
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
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 Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!