Need help with for loops
4 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
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
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
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!