How can I store data from a nested for loop?
显示 更早的评论
Hello guys, I'm new to this website. I need help with the following problem. I would like to store the values of V and P in two vectors so that I can plot them afterwards. As you can see, in the first loop, I vary the parameter "P1" three times because I have to obtain the values at +/- 25 percent of the original value of P1. As a result, this affects the values of V and P. Thus, since I'm changing the value of P1 three times, I should get three different values for V and P. With these three values (i.e., V = [ a b c] and P = [f g h], I want to construct a V vs P plot. Can someone help me how to do this? I keep getting the error: "in an assignment A(I) = B, the number of elements in B and I must be the same"(please run the code I have attached, thank you). The code seems to work at the beginning but then it stops. Thanks in advance!
P2 = 680;
H = 125;
A = 8;
B = 15;
C = 5.2;
% initial guesses
P(1) = 50; % pressure
V(1) = 80; % flow rate
eps = 0.00001;
for i = 1:3
P1(i) = 225+450.*0.25.*i;
for j = 1:50
v1 = sqrt((P1(i)-P)/A)+sqrt((P2-P)/B)-V;
p1 = H+C*(V.^2)-P;
b = v1.^2+p1.^2;
% check for convergence
if b<eps
disp('the required solution is: ')
fprintf('The flow rate is V = %.4f The pressure P = %.4f\n',V(i),P(i))
disp(' ')
break
end
% calculate partial derivatives
vv = -1;
vp = (1/2)*(((P1(i)-P)/A).^(-1/2))*(-1/A)+(1/2)*(((P2-P)/B).^(-1/2))*(-1/B);
pv = 2*C*V;
pp = -1;
d = vv.*pp-vp.*pv;
% determine the increments
dv = (-v1.*pp+p1.*vp)/d;
dp = (-p1.*vv+v1.*pv)/d;
% calculate the values of v and p for next iteration
V(i) = V+dv;
P(i) = P+dp;
% print results
fprintf('P1 = %.4f\t V = %.6f\t P = %.6f\n',P1(i),V(i),P(i))
end
end
1 个评论
CS Researcher
2016-5-2
Check the following:
V(i) = V + dv
V(i) is a scalar while V becomes a vector. Same for P(i)
回答(1 个)
Star Strider
2014-12-5
0 个投票
I ran your code but encountered problems with ‘dv’ and ‘dp’ being matrices. I can’t figure out what you want to do with those variables, so I suggest you check the sizes of your various variables and code them to be what you want.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!