필터 지우기
필터 지우기

Indexing issue- using negative values in for loop calculations.

조회 수: 3 (최근 30일)
Shrishti Yadav
Shrishti Yadav 2021년 10월 30일
댓글: Shrishti Yadav 2021년 10월 30일
I would like to store the values Zx and Zy from the code below in Z but not sure how.
clc;
u = 4
Z = zeros(u*u,1);
cx = 1;
cy = 1;
r = 3;
for j = 1:(u*u)
for x = -u:u
for y = -u:u
theta = atan2((y-cy) ,(x-cx));
Zx = cx-r*cos(theta)
Zy = cy - r*sin(theta)
Z(j,1) = (Zx);
Z(j,2) = (Zy);
end
end
end

채택된 답변

DGM
DGM 2021년 10월 30일
It's not clear why you're overwriting your results and then repeating the process 16 times anyway. If you want Z for all x and all y, then the outer loop doesn't do anything.
u = 4;
Z = zeros(u*u,1);
cx = 1;
cy = 1;
r = 3;
x = -u:u;
y = (-u:u).';
theta = atan2((y-cy) ,(x-cx));
Zx = cx - r*cos(theta)
Zx = 9×9
3.1213 2.8741 2.5435 2.1142 1.5883 1.0000 0.4117 -0.1142 -0.5435 3.3426 3.1213 2.8000 2.3416 1.7276 1.0000 0.2724 -0.3416 -0.8000 3.5725 3.4000 3.1213 2.6641 1.9487 1.0000 0.0513 -0.6641 -1.1213 3.7854 3.6833 3.4962 3.1213 2.3416 1.0000 -0.3416 -1.1213 -1.4962 3.9417 3.9104 3.8460 3.6833 3.1213 1.0000 -1.1213 -1.6833 -1.8460 4.0000 4.0000 4.0000 4.0000 4.0000 -2.0000 -2.0000 -2.0000 -2.0000 3.9417 3.9104 3.8460 3.6833 3.1213 1.0000 -1.1213 -1.6833 -1.8460 3.7854 3.6833 3.4962 3.1213 2.3416 1.0000 -0.3416 -1.1213 -1.4962 3.5725 3.4000 3.1213 2.6641 1.9487 1.0000 0.0513 -0.6641 -1.1213
Zy = cy - r*sin(theta)
Zy = 9×9
3.1213 3.3426 3.5725 3.7854 3.9417 4.0000 3.9417 3.7854 3.5725 2.8741 3.1213 3.4000 3.6833 3.9104 4.0000 3.9104 3.6833 3.4000 2.5435 2.8000 3.1213 3.4962 3.8460 4.0000 3.8460 3.4962 3.1213 2.1142 2.3416 2.6641 3.1213 3.6833 4.0000 3.6833 3.1213 2.6641 1.5883 1.7276 1.9487 2.3416 3.1213 4.0000 3.1213 2.3416 1.9487 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 0.4117 0.2724 0.0513 -0.3416 -1.1213 -2.0000 -1.1213 -0.3416 0.0513 -0.1142 -0.3416 -0.6641 -1.1213 -1.6833 -2.0000 -1.6833 -1.1213 -0.6641 -0.5435 -0.8000 -1.1213 -1.4962 -1.8460 -2.0000 -1.8460 -1.4962 -1.1213
If you want Zx and Zy to be reshaped as column vectors, figure out how you want them reshaped:
Z = [Zx(:) Zy(:)]
Z = 81×2
3.1213 3.1213 3.3426 2.8741 3.5725 2.5435 3.7854 2.1142 3.9417 1.5883 4.0000 1.0000 3.9417 0.4117 3.7854 -0.1142 3.5725 -0.5435 2.8741 3.3426

추가 답변 (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