MATLAB: How to redo it by using for loop

function [x,y] = butterfly_function(tmin,tmax,dt,s,x0,y0)
%BUTTERFLY_FUNCTION Summary of this function goes here
% Detailed explanation goes here
t=tmin:dt:tmax;
f=exp(cos(t))-2*cos(4*t)-(sin(t/12)).^5;
x=x0+(s.*f.*sin(t));
y=y0+(s.*f.*cos(t));
end
---------------------------------
Matlab code for main program
-----------------
tmin=0;
tmax=40*pi;
dt=0.001;
s=0.1;
x0=1;
y0=1;
[x,y] = butterfly_function(tmin,tmax,dt,s,x0,y0);
plot(x,y,'b')
axis([0 4 0 4])
axis equal
hold on
s=0.4;
x0=2.5;
y0=1;
[x,y] = butterfly_function(tmin,tmax,dt,s,x0,y0);
plot(x,y,'r')
hold on
s=0.2;
x0=0.5;
y0=3;
[x,y] = butterfly_function(tmin,tmax,dt,s,x0,y0);
plot(x,y,'k')
hold on

Best Answer

ASA - I suppose if it is the main part of your code that you wish to iterate/loop over, you could do something like
tmin=0;
tmax=40*pi;
dt=0.001;
s = [0.1 0.4 0.2];
x0 = [1 2.5 0.5];
y0 = [1 1 3];
c = {'b', 'r','k'};
for k=1:length(s)
[x,y] = butterfly_function(tmin,tmax,dt,s(k),x0(k),y0(k));
plot(x,y,c{k})
hold on
end
Try the above and see what happens! Note how the code just takes those elements that are variable and creates arrays out of them. We then iterate over each element in the array to call the butterfly_function.
Related Question