Calling a function in function considering a loop
조회 수: 9 (최근 30일)
이전 댓글 표시
Hi
I have a function like c=F(i,j)
I want to create a loop in my function as below
for p=1:4
c=c+x*F(i-p,j)
end
I want to have this
c=F(3,1) + F(2,1) +F(1,1)
By doing that, unfortunetaly, the MATLAB does not condider all the loops and when i=i-p, it immidiately goes out from the function and just consider F(3,1)
I appreciate that if u tell me how i can do sth like this.
댓글 수: 2
KSSV
2022년 9월 5일
Show us your full code along with the function F. Are you running a loop for i,j ??
답변 (1개)
Mathieu NOE
2022년 9월 5일
hello
here you are.
NB I prefered not to use the same "c" variable name both in the function and in the main loop - not that it's forbidden or a coding mistake, simply this is prone to errors and does not ease the code reading / debugging.
% init
c = 0; % init c = zero
i = 4;
j = 1;
x = 1;
% main code
for p = 1:3
c = c+x*F(i-p,j);
end
% function
function out = F(i,j)
out = 5*i + 10*j;
end
댓글 수: 3
Rik
2022년 9월 5일
It sounds like you need recursion. But more importantly: you need to thouroughly describe what you actually need. Where are y and z suddenly coming from?
The only viable path to a good solution is a good description of the problem.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!