build an array within the loop

2 ビュー (過去 30 日間)
Aamna Alshehhi
Aamna Alshehhi 2019 年 10 月 2 日
コメント済み: Aamna Alshehhi 2019 年 10 月 2 日
i wanna build two arrays within a loop. the first array contain Th2 elements and the second array contain Th3 elements. then i wanna plot them. this my code
for Th2=0:360
d =3.5; a = 1;b = 2; c = 4;
Th1= 0;
Z = d*exp(1i*deg2rad(Th1))- a*exp(1i*deg2rad(Th2));
Zc = conj(Z);
Ka = c*Zc; Kb = Z*Zc + c^2 -b^2; Kc = c*Z;
T = roots([ Ka Kb Kc]);
S = (c*T+Z)/b;
Th3 = rad2deg(angle(S));
Th4 = rad2deg(angle(T));
P= a*exp(1i* deg2rad(Th1))+ 6*exp(1i* deg2rad(Th3+20));
end
plot (Th2,Th3);

採用された回答

Charles Rice
Charles Rice 2019 年 10 月 2 日
Each time through the loop, Th3 is being overwritten with a new value. You need to assign each new value to the next index in an array.
theta_range = 0:360; % create the range of angles
Th3 = zeros(2, numel(theta_range)); % preallocate array
Th4 = zeros(2, numel(theta_range)); % preallocate array
for theta_index = 1:numel(theta_range)
% step through angles (this helps avoid zero indexing and lets you have a non-integer range)
Th2 = theta_range(theta_index);
d = 3.5;
a = 1;
b = 2;
c = 4;
Th1= 0;
Z = d*exp(1i*deg2rad(Th1)) - a*exp(1i*deg2rad(Th2));
Zc = conj(Z);
Ka = c*Zc;
Kb = Z.*Zc + c^2 - b^2;
Kc = c*Z;
T = roots([ Ka Kb Kc]);
S = (c*T+Z)/b;
Th3(:, theta_index) = rad2deg(angle(S)); % this function gives you a 2x1 result, so put it in both rows
Th4(:, theta_index) = rad2deg(angle(T));
P = a*exp(1i* deg2rad(Th1))+ 6*exp(1i* deg2rad(Th3+20));
end
subplot(2,1,1)
plot(theta_range, Th3(1,:));
xlabel('Theta')
ylabel('Positive Theta 3')
subplot(2,1,2)
plot(theta_range, Th3(2,:));
xlabel('Theta')
ylabel('Negative Theta 3')
  1 件のコメント
Aamna Alshehhi
Aamna Alshehhi 2019 年 10 月 2 日
THANKS SO MUCH!!

サインインしてコメントする。

その他の回答 (1 件)

Ajay Kumar
Ajay Kumar 2019 年 10 月 2 日
You are not creating Th3 array but overwriting it everytime. Try this
for i=0:360
d =3.5; a = 1;b = 2; c = 4;
Th1= 0;
Z = d*exp(1i*deg2rad(Th1))- a*exp(1i*deg2rad(i));
Zc = conj(Z);
Ka = c*Zc; Kb = Z*Zc + c^2 -b^2; Kc = c*Z;
T = roots([ Ka Kb Kc]);
S = (c*T+Z)/b;
Th3(:,i+1) = rad2deg(angle(S));
Th4 = rad2deg(angle(T));
P= a*exp(1i* deg2rad(Th1))+ 6*exp(1i* deg2rad(Th3+20));
end
Th2 = 0:360;
plot (Th2,Th3(1,:));
hold on;
plot (Th2,Th3(2,:));
  1 件のコメント
Aamna Alshehhi
Aamna Alshehhi 2019 年 10 月 2 日
you guys are AMAZING. THANKS!!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOceanography and Hydrology についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by