How to plot recursive definition in Matlab/Simulink?

Illustration
Sammy - 2021-09-03T12:28:59+00:00
Question: How to plot recursive definition in Matlab/Simulink?

where n is 1 to 10   A(n)=1.03*A(n-1)-700;   B(n)=(B(n-1)+50)*1.03;   (n-1) being the previous term of n   is it possible to plot those recursive definitions as two lines on the same graph in Matlab?   if so how?

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

Use a while loop and call functions for each. However, for this problem, consider using a for loop. It will be much more efficient since you can use the values immediately previous.
 
You will need to define A(1) and B(1). I'll assume them to be 1 here.
 
nmx = 10;

% Assuming A(1) and B(1) are 1, because they weren't otherwise defined.
A = ones(nmx,1);
B = ones(nmx,1);
for ix=2:nmx
    A(ix) = 1.03*A(ix-1)-700;
    B(ix) = 1.03*(B(ix-1)+50);
end

% Call the recursive function for each value of n
Ar = ones(nmx,1);
Br = ones(nmx,1);
for ix=1:nmx
    [Ar(ix)] = A_recurse(ix);
    [Br(ix)] = B_recurse(ix);
end

figure(1)
plot(1:nmx,A,'p');
hold on
plot(1:nmx,B,'o');
plot(1:nmx,Ar,'s');
plot(1:nmx,Br,'x');
hold off
legend('A','B','Ar','Br');


function A = A_recurse(n)
if n == 1
    A = 1;
else
    A = 1.03*A_recurse(n-1)-700;
end
end

function B = B_recurse(n)
if n == 1
    B = 1;
else
    B = 1.03*(B_recurse(n-1)+50);
end
end
    
function A = A_recurse(n)
if n == 1
    A = 1;
else
    A = 1.03*A_recurse(n-1)-700;
end
end
function B = B_recurse(n)
if n == 1
    B = 1;
else
    B = 1.03*(B_recurse(n-1)+50);
end
end
    


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!