Need help with for loops

4 views (last 30 days)
Abdullah Al-Alawi
Abdullah Al-Alawi on 18 Oct 2017
Commented: KL on 18 Oct 2017
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.

Answers (1)

Image Analyst
Image Analyst on 18 Oct 2017
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 Comments
Abdullah Al-Alawi
Abdullah Al-Alawi on 18 Oct 2017
Edited: Abdullah Al-Alawi on 18 Oct 2017
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 on 18 Oct 2017
You need to store the outcome of each iteration in a matrix, for example,
UB1(:,k) = u.*cos(w.*t); %similarly for other variables

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!