# How can I put the results from a while loop in a matrix?

1 view (last 30 days)
Kaicheng Pan on 14 May 2020
Commented: Kaicheng Pan on 14 May 2020
So basically I am solving an equation using trial and error. Here's the code
clear;clc;
syms x y
a1=13.7819; b1=2726.81; c1=217.512;
a2=13.9726; b2=3259.93; c2=212.3;
for x=0:10
t=70;
psat1=exp(a1-b1/(t+c1));
psat2=exp(a2-b2/(t+c2));
p=0.1*x*psat1+(1-0.1*x)*psat2;
while abs(p-90)>5
t=t+1;
psat1=exp(a1-b1/(t+c1));
psat2=exp(a2-b2/(t+c2));
p=0.1*x*psat1+(1-0.1*x)*psat2;
end
t(x+1)=t
end
I want to put the t from each for loop into one matrix, but Matlab spits out this:
t=131
t=119 119
t=111 0 111
t=103 0 0 103 and so on

Geoff Hayes on 14 May 2020
Kaicheng - you probably can remove the line
syms x y
since I can't see the y being used in the code, and the x is overridden by the loop step variable. A problem is that you are treating t as if it were an array (at one line of code) and then as a scalar (at another line of code)
for x=0:10
t=70; % <---- here t is a scalar and is being reset on each iteration
psat1=exp(a1-b1/(t+c1));
psat2=exp(a2-b2/(t+c2));
p=0.1*x*psat1+(1-0.1*x)*psat2;
while abs(p-90)>5
t=t+1;
psat1=exp(a1-b1/(t+c1));
psat2=exp(a2-b2/(t+c2));
p=0.1*x*psat1+(1-0.1*x)*psat2;
end
t(x+1)=t % <---- here t is an array
end
Try creating an array for your t values:
tArray = zeros(11,1);
for x=0:10
t=70;
psat1=exp(a1-b1/(t+c1));
psat2=exp(a2-b2/(t+c2));
p=0.1*x*psat1+(1-0.1*x)*psat2;
while abs(p-90)>5
t=t+1;
psat1=exp(a1-b1/(t+c1));
psat2=exp(a2-b2/(t+c2));
p=0.1*x*psat1+(1-0.1*x)*psat2;
end
tArray(x+1)=t;
end
I'm assuming that you mean to reset t to 70 on each iteration of the loop. Is this correct?

#### 1 Comment

Kaicheng Pan on 14 May 2020
Thank you so much! It solves my problem perfectly. I should use a new array to put my t values in.