Need help with for loops

조회 수: 3 (최근 30일)
Abdullah Al-Alawi
Abdullah Al-Alawi 2017년 10월 18일
댓글: KL 2017년 10월 18일
t = [0:20]; %time domain u = [1 0.6 0.3 0.1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; %input y = [0 0.5 0.9 0.91 0.866 0.732 0.612 0.513 0.43 0.361 0.302 0.253 0.212 0.178 0.149 0.125 0.105 0.088 0.074 0.062 0.052];%output
for w = linspace(0, 2*pi, 100); %w is frequency. I want it to varies.
UB1 = u.*cos(w.*t);
UB2 = u.*sin(w.*t);
YA1 = y.*cos(w.*t);
YA2 = y.*sin(w.*t);
B1 = trapz(UB1);
B2 = trapz(UB2);
A1 = trapz(YA1);
A2 = trapz(YA2);
AR = sqrt(((A1)^2+(A2)^2)/((B1)^2 + (B2)^2));
end
% I want w to vary. for example, starting with w being zero, I want the code to calculate UB1,UB2, etc for each w using the data that was given in the matrices, t, u, and y.

답변 (1개)

Image Analyst
Image Analyst 2017년 10월 18일
Perhaps this:
t = [0:20]; %time domain
u = [1 0.6 0.3 0.1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; %input
y = [0 0.5 0.9 0.91 0.866 0.732 0.612 0.513 0.43 0.361 0.302 0.253 0.212 0.178 0.149 0.125 0.105 0.088 0.074 0.062 0.052];%output
wArray = linspace(0, 2*pi, length(t)); %w is frequency. I want it to varies.
for k = 1 : length(wArray)
w = wArray(k);
UB1 = u.*cos(w.*t);
UB2 = u.*sin(w.*t);
YA1 = y.*cos(w.*t);
YA2 = y.*sin(w.*t);
B1 = trapz(UB1);
B2 = trapz(UB2);
A1 = trapz(YA1);
A2 = trapz(YA2);
AR = sqrt(((A1)^2+(A2)^2)/((B1)^2 + (B2)^2));
end
But the variables inside the loop at 21 element vectors, and you're not doing anything with them - you're just overwriting them at each iteration.
  댓글 수: 2
Abdullah Al-Alawi
Abdullah Al-Alawi 2017년 10월 18일
편집: Abdullah Al-Alawi 2017년 10월 18일
Thank you for your response. However, this does not solve my B1,B2,A1,A2 and AR. At the end, I would like an AR value for each frequency, so I can plot AR vs t.
So I am expecting for each UB1 to YA2 to have multiple rows each at different frequency, w. so I can integrate each row using the trapz function, and then calculating AR.
For example, w = 0 UB1= [x x x x x...] next w = pi UB1 = [x x x x x... y y y y y ...]and so on then B1 calculates trapz for EACH row. then AR calculates for each row of B1,B2,A1, A2. So at the end, I will plot AR for each frequency.
KL
KL 2017년 10월 18일
You need to store the outcome of each iteration in a matrix, for example,
UB1(:,k) = u.*cos(w.*t); %similarly for other variables

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

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by