Data in array being overwritten when if statement is satisfied.

The first part of my array Cur2 is populated with 0 as I would expect from the following IF statement. When the IF statement is satisfied and the equation in the ELSE statement is used the first half of the array is overwritten with the value that would be calculated by the eq'n.
clearvars
L=80*10^3; x1=0:1000:1.5*10^5; U= 0.2; t1=x1./U;
Cs= 9; C0= 8;
M0 = 0.75*10^6;
M1= M0;
Q= 50*10^3;
Kr=0.4/24/60/60; Kd=Kr; Ka=0.8/24/60/60;
for n = 1:151
Cur1(1:n) = Kd*M0*(exp(-t1(1:n)*Kr)-exp(-t1(1:n)*Ka))/(Q*(Ka-Kr));
if (n<= 80)
Cur2(1:n) = 0;
else
Cur2(1:n) = Kd*M1*(exp(-((x1(1:n)-L)/U)*Kr)-exp(-((x1(1:n)-L)/U)*Ka))/(Q*(Ka-Kr));
end
C(1:n) = Cs - Cur1(1:n) - (Cs- C0)*exp(-t1(1:n)*Ka)-Cur2(1:n);
end
plot(x1,C);

 採用された回答

Stephen23
Stephen23 2016 年 7 月 27 日
編集済み: Stephen23 2016 年 7 月 27 日

0 投票

Your data is being "overwritten" because that is what you wrote your code to do:
Cur2(1:n) = 0;
puts zeros in elements 1 to n. The your else puts something else in elements 1 to n:
Cur2(1:n) = Kd*M1*(...)
What do you want your code to do ?

4 件のコメント

Nathan Dick
Nathan Dick 2016 年 7 月 27 日
Thanks for the reply. I want the first 80 entries to be 0 then the rest to populated by the value of the function Cur2. I tried an ELSEIF > 80 thinking that ELSE statements might be cause.
Haven't done much on MATLAB but I thought what I was asking it to do was for every iteration of the FOR loop check whether the value of n <=80 and if this was true that entry in the matrix Cur2 would be 0 ELSE it would be calculated by the function.
Stephen23
Stephen23 2016 年 7 月 27 日
編集済み: Stephen23 2016 年 7 月 27 日
"that entry in the matrix"
Not just that entry, because you are specifying all entries from 1 to n, and so all of those entries get replaced. If you want to specify that you replace only one entry, then whey are you indexing all entries from 1 to n ? Basically you are doing this:
>> X = 1:9
X =
1 2 3 4 5 6 7 8 9
>> X(1:5) = 0
X =
0 0 0 0 0 6 7 8 9
>> X(1:6) = 1
X =
1 1 1 1 1 1 7 8 9
Perhaps you meant to do this:
Cur2(n) = Kd*M1*(...)
You should really learn about these basic indexing concepts, otherwise using MATLAB will be very inefficient and difficult. The best place to start are these tutorials:
Nathan Dick
Nathan Dick 2016 年 7 月 27 日
Thanks again for the reply. That is exactly what I meant. I got the syntax confused as I though by using(1:n) I was simply saying that it was a 1D array. For uni I have done some VB but this current course requires MATLAB so it is a learning experience.
Stephen23
Stephen23 2016 年 7 月 27 日

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2016 年 7 月 27 日

コメント済み:

2016 年 7 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by