フィルターのクリア

Strange If- else statement issue

1 回表示 (過去 30 日間)
Numan
Numan 2012 年 7 月 24 日
Hi, Iam trying to write a very simple program. That is the program i wrote:
t=1:1:8760
k=rem(t,24)
if k(1,t)<10 & k(1,t)>1
Ca(t)=10
elseif k(1,t)<20 & k(1,t)>10
Ca(t)=20
else
Ca(t)=40
end
I just want that if the k(1,t) is between 1 and 10, Ca(t) should be 10. So for k(1,t)=1,2,3...9, it should be Ca(1)=10, Ca(2)= 10.... Ca(9)=10.
if the k(1,t) is between 10 and 20, Ca(t) should be 20. So for k(1,t)=10,11...,19, it should be Ca(11)=20, Ca(12)= 20.... Ca(19)=20.
else it should be, Ca(t)=40 (Ca(21)=40, Ca(22)=40...)
But i get as result always Ca(t)=40. So i get for all values of t, the result 40.
What am i doing wrong?
Thanks

採用された回答

Honglei Chen
Honglei Chen 2012 年 7 月 24 日
編集済み: Honglei Chen 2012 年 7 月 24 日
There are several issues.
  1. k(1,t) < 10 returns a vector, not a scalar
  2. Similarly, Ca(t) is a vector.
  3. It looks like you really want to loop through all the elements and if that's the case, you need to deal with one t a time
  4. If above is true, you probably want to use && instead of &
  5. Based on all above, you can see that your current script is only executed once and it lands in the last condition.
  6. Finally, you may want to consider vectorizing the code using logical index and in that case you do want to use &, not &&. As an example:
Ca = 40*ones(size(t));
Ca(k(1,t)<10 & k(1,t)>1) = 10;
  2 件のコメント
Numan
Numan 2012 年 7 月 24 日
but if i ask for k(1,10) for example i get an scalar answer, so the result of k(1,t) is scalar i guess.
How should i deal with one t at a time?
Whats is the differance between one & and two?
Lastly how can i fix the problem?
Honglei Chen
Honglei Chen 2012 年 7 月 24 日
Your t is a vector, that's why the result of k(1,t) is a vector. If you want to deal with them one at a time, you should use a loop, for example,
for m = 1:numel(t)
if k(1,m)<10 && k(1,m)>1
Ca(m)=10
end
end
But in this case you should use &&, not &.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by