store variables in a for loop

6 views (last 30 days)
Hello,
i m trying to obtain a set of coordinates for this:
function [x, y] = gencircle(xo,yo,r,N)
x=(xo+r*cos(theta))';
y=(yo+r*sin(theta))';
clear all
xo=[1 2 3 4 5 6 7 8];
yo=[-1 -0.5];
r=0.01;
N=10;
theta=2*pi/N*(1:N+1);
th=0.00235;
for j=1:length(yo)
for i=1:length(xo)
[xout(:,i), yout(:,j)]=gencircle(xo(i),yo(j),r,N)
[xin(:,i), yin(:,j)]=gencircle(xo(i),yo(j),r-th,N)
end
end
for j=1:length(yo)
for i=1:length(xo)
aa=[xout(:,i),yout(:,j)]
end
end
how can i store the vector aa for each loop?
Thanks

Accepted Answer

Sriram Tadavarty
Sriram Tadavarty on 21 Apr 2020
Edited: Sriram Tadavarty on 21 Apr 2020
Hi Davide,
You can make the following modification to the code as shown below, which stores all the loop iteration values in the variable aa:
clear all
xo=[1 2 3 4 5 6 7 8];
yo=[-1 -0.5];
r=0.01;
N=10;
theta=2*pi/N*(1:N+1);
th=0.00235;
for j=1:length(yo)
for i=1:length(xo)
[xout(:,i), yout(:,j)]=gencircle(xo(i),yo(j),r,theta);
[xin(:,i), yin(:,j)]=gencircle(xo(i),yo(j),r-th,theta);
end
end
aa = zeros(size(xout,1),2,length(yo)*length(xo)); % Initialize the variable
tmp = 1;
for j=1:length(yo)
for i=1:length(xo)
aa(:,:,tmp)=[xout(:,i),yout(:,j)];
tmp = tmp+1;
end
end
% aa will be a variable of size length(xout) x 2 x (loop iterations)
% loop iterations here is equal to the product of length(yo) and length(xo) (implies 16)
% Each iteration value can be accessed by indexing from 3rd dimension,
% implies for example fifth iteration can be accessed with aa(:,:,5)
function [x, y] = gencircle(xo,yo,r,theta)
x=(xo+r*cos(theta))';
y=(yo+r*sin(theta))';
end
Hope this helps.
Regards,
Sriram
  4 Comments
Davide Cerra
Davide Cerra on 21 Apr 2020
incredibly useful, thanks!
Sriram Tadavarty
Sriram Tadavarty on 21 Apr 2020
Please do accept the answer, if helped

Sign in to comment.

More Answers (0)

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!