Loop not working properly

조회 수: 1 (최근 30일)
Tom
Tom 2019년 8월 11일
편집: the cyclist 2019년 8월 11일
I have a piece of code which creates a 3 x 46 array
theta = 0;
phi = pi/4;
r = 1 : 0.2 : 10;
theta = repmat(theta,size(r));
phi = repmat(phi, size(r)); %obtain position vectors for the points along a radial line where the velocities are evaluated%
[x,y,z] = sph2cart(theta,phi,r);
p = [x; y; z];
I then have a loop where you evaluate a function of the distance from each point represented in this array to a set of other points forming a 3 x 100 array:
for II=1:46
for IJ=1:100
normal=(p(1:3,II)/(norm(p(1:3,II))))';
r=(p(1:3,II)-sing(1:3,IJ))';
A((1+(II-1)*3):(3+(II-1)*3),(1+(IJ-1)*3):(3+(IJ-1)*3))=gradletSlip(r,in)';
end
end
However, something seems to be wrong as when I loop through IJ the number changes as it is a different distance each time, but when II changes from 1 to 2, it is supposed to be at another point in the 3 x 46 array and yet the normal is not changing, but this is just the radial vector, so it seems like it is not moving to the new point in the 3 x 46 array as it does the loop. Any idea how to fix this?

채택된 답변

the cyclist
the cyclist 2019년 8월 11일
What you are observing seems correct to me.
theta is 0, and phi is constant. This means that even as r increases
  • y is zero (because theta is 0)
  • x and z increase in proportion to each other
(You can see this is true in the xyz array, if you place a breakpoint and look at the values).
Therefore, the normal vector always points in the same direction -- and is constant because it is also normalized.
All seems well.
Side note:
You can take the calculation
normal=(p(1:3,II)/(norm(p(1:3,II))))';
outside of the IJ loop, because its value doesn't depend on IJ. Just calculate it once for ever II loop.
  댓글 수: 2
Tom
Tom 2019년 8월 11일
Hmm, I've tried setting theta to pi/2, for example, and still get that the normal is always the same, I suppose if theta and phi are both constant, the normal always points in the same direction and then after normalisation, you are going to have the same vector as for the unit sphere?
the cyclist
the cyclist 2019년 8월 11일
편집: the cyclist 2019년 8월 11일
Sounds right to me. By construction, xyz is a vector where only the radius increases, so the normal vector would remain constant (but different for different choices of theta and phi).

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by