Calling a function in function considering a loop

8 views (last 30 days)
Mohsen
Mohsen on 5 Sep 2022
Edited: Rik on 5 Sep 2022
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 Comments
KSSV
KSSV on 5 Sep 2022
Show us your full code along with the function F. Are you running a loop for i,j ??
Mohsen
Mohsen on 5 Sep 2022
Edited: Rik on 5 Sep 2022
function CB=F(i,j)
global Z
N=3;
CB=0;
TC=[7,4,5,6,5,8];
LL=[2,3,1,1,1,1];
persistent G
if isempty(G)
G=ones(N,1);
end
if i==1
for p=1:(N-1)
G(i,1)=0;
if G(p+i,1)==0
CB=CB+TC(1)/(N-1);
else
CB=LL(p)*G(1+p,1)*A(1+p,j)+TC(1)/(N-1);
end
end
elseif i==N
for p=1:(N-1)
G(i,1)=0;
CB=CB+LL(p)*G(i-p,1)*B(i-p,j)+TC(i)/(N-1);
end
else
for p=1:(i-1)
G(i,1)=0;
if (G(i-p,1)==0)
continue;
else
CB=CB+LL(p)*G(i-p,1)*B(i-p,j)+TC(i)/(i-1);
end
end
for p=1:(N-i)
if (G(i+p,1)==0)
continue;
else
CB=LL(p)*G(i+p,1)*A(i+p,j);
end
end
end
end
function a=A(i,j)
global Z
global G
Z=i;
G(i,1)=0;
a=F(i,j);
end

Sign in to comment.

Answers (1)

Mathieu NOE
Mathieu NOE on 5 Sep 2022
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 Comments
Rik
Rik on 5 Sep 2022
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.
Mohsen
Mohsen on 5 Sep 2022
Well z and y are 2 constants.
As you mentioned, I surely need recursion.
The F(i,j) is a function of F(i-p,j) where p=1:i.
So
F(i,j)=constant*F(i-1,j) + constant*F(i-2,j)+ ... + constnat*F(1,j) eq(1)
And again
F(i-1,j)= onstant*F(i-2,j) + constant*F(i-3,j)+ ... + constnat*F(1,j).
Until
F(2,j)= constant*F(1,j)
The problem is that in the eq(1) the for loop does not run completely and when the compiler reachs F(i-1,J). It goes out from the loop.
At the first step, I want the loop runs completely and then all functions (F(i-1,j) ...) recall.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!