Calling a function in function considering a loop
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
KSSV
le 5 Sep 2022
Show us your full code along with the function F. Are you running a loop for i,j ??
Réponses (1)
Mathieu NOE
le 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 commentaires
Rik
le 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.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!