필터 지우기
필터 지우기

write 3 for loops in each other

조회 수: 6 (최근 30일)
Hamed Nobarani
Hamed Nobarani 2018년 9월 28일
댓글: Hamed Nobarani 2019년 11월 11일
I should write the program to get the positions x,y,z (lattice points) and then repeat these positions(lattice cube) in the x,y,z direction with the constant(lattice constant).my code is just working in one direction(x), how can I fix my code to work in all 3 x,y,z directions?
for k=0:o
for j=0:m
for i=0:n
xpp(8*i+1:8*i+8,1)=xp+D*i;
ypp(8*i+1:8*i+8,1)=yp+D*j;
zpp(8*i+1:8*i+8,1)=zp+D*k;
end
end
end
%start
a=importdata('structure.xyz');
xp=a.data(:,1);
yp=a.data(:,2);
zp=a.data(:,3);
n=1;
m=1;
o=1;
xpp=xp;
ypp=yp;
zpp=zp;
for k=0:o
for j=0:m
for i=0:n
xpp(8*i+1:8*i+8,1)=xp+D*i;
ypp(8*i+1:8*i+8,1)=yp+D*j;
zpp(8*i+1:8*i+8,1)=zp+D*k;
end
end
end
fileID = fopen('N.txt','w');
fprintf(fileID,'%s\n','silicon');
fprintf(fileID,'si %f %f %f\n',[xpp,ypp,zpp].');
fclose(fileID);
  댓글 수: 1
JohnGalt
JohnGalt 2018년 10월 1일
what's D? what's the for loop at the start of your question (before '%start')? Can you give an example with some very small amount of data? are trying to create a grid starting from a specific point with a specific separation?

댓글을 달려면 로그인하십시오.

채택된 답변

Hamed Nobarani
Hamed Nobarani 2019년 11월 11일
편집: Rik 2019년 11월 11일
I was trying to get the unit cell of the structure which is contain positions of atoms and then expand it in 3 dimensions.
this is my code and answer to this question:
l=0;
s=0;
for k=1:o
for j=1:m
for i=1:n
nb=[xp+D*(i-1),yp+D*(j-1),zp+D*(k-1)];
pp(s+1:s+8,:)= nb;
s=s+8;
l=(l+1);
end
end
end
  댓글 수: 2
Rik
Rik 2019년 11월 11일
The code below is equivalent to what you wrote, but should be slightly faster.
pp=zeros(o*m*n*8,3);%or: pp=zeros([o*m*n 1].*size([xp,yp,zp]))
s=0;
for k=1:o
for j=1:m
for i=1:n
nb=[xp+D*(i-1),yp+D*(j-1),zp+D*(k-1)];
pp(s+1:s+8,:)= nb;
s=s+8;
end
end
end
l=o*m*n;
You should try to avoid l and o as variable names, because they look very similar to 1 and 0. It also looks like it should be possible to do this with meshgrid and reshape, which would avoid the loops.
Hamed Nobarani
Hamed Nobarani 2019년 11월 11일
Thanks Rik.
Sure,I got it.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Karun Mathiazhagan
Karun Mathiazhagan 2018년 10월 3일
Hello Hamed,
If my understanding is correct that you wish to create a 3-D grid of points similar to a lattice structure, the following MATLAB Answers post should be of use to you: https://www.mathworks.com/matlabcentral/answers/98191-how-can-i-obtain-all-possible-combinations-of-given-vectors-in-matlab

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by