フィルターのクリア

Vector output from a for loop

4 ビュー (過去 30 日間)
Sercan Yalcin
Sercan Yalcin 2019 年 12 月 5 日
コメント済み: Sercan Yalcin 2019 年 12 月 6 日
Hello everyone,
I have an hourly temperature data which covers 8760 values inside a vector. The TMP shows the temperature values however the values below in the code is just for example since i can't put 8760 values here.
I want to get PGRED results as a vector output too. However, when i run the code, although it calculates PGRED values for all TMP values, i get an answer only for the last TMP value which is 36 in this case. My question is, how can i get all the PGRED answers inside 1 vector.
Thank you for your help in advance.
for TMP =[12, 3, 36]
if TMP < 9
PGRED=0
elseif 9<=TMP & TMP<10
PGRED= TMP-9
elseif 10<=TMP & TMP<28
PGRED= 1
elseif 28<=TMP & TMP<40
PGRED= -0.083*TMP + 3.33
else 40 >= TMP
PGRED=0
end
end

採用された回答

Raj
Raj 2019 年 12 月 5 日
編集済み: Raj 2019 年 12 月 5 日
TMP =[12, 3, 36];
PGRED=zeros(size(TMP));
for ii=1:length(TMP)
if TMP(ii) < 9
PGRED(ii)=0;
elseif 9<=TMP(ii) && TMP(ii)<10
PGRED(ii)= TMP(ii)-9;
elseif 10<=TMP(ii) && TMP(ii)<28
PGRED(ii)= 1;
elseif 28<=TMP(ii) && TMP(ii)<40
PGRED(ii)= -0.083*TMP(ii) + 3.33;
else %40 >= TMP(ii) % this condition is not required. Just give a default condition.
PGRED(ii)=0;
end
end

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2019 年 12 月 5 日
TMP_values = [12, 3, 36];
num_TMP = length(TMP_values);
PGRED = zeros(1, num_TMP);
for TMP_idx = 1 : num_TMP
TMP = TMP_values(TMP_idx);
if TMP < 9
PGRED(TMP_idx) = 0;
elseif 9<=TMP & TMP<10
PGRED(TMP_idx) = TMP-9;
elseif 10<=TMP & TMP<28
PGRED(TMP_idx) = 1;
elseif 28<=TMP & TMP<40
PGRED(TMP_idx) = -0.083*TMP + 3.33;
elseif 40 >= TMP
PGRED(TMP_idx) = 0;
else
error('Unexpected out of range TMP = %f', TMP)
end
end
This is not what I would recommend for this situation: I would recommend that you learn how to use logical indexing. However, I do recommend that you learn to use this pattern, of storing all of the values in a vector and indexing over the length of the vector and using the index to store the results.
  1 件のコメント
Sercan Yalcin
Sercan Yalcin 2019 年 12 月 6 日
Thank you for the suggestion, i will check logical indexing out!

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


Andrei Bobrov
Andrei Bobrov 2019 年 12 月 5 日
TMP = randi([-12,45],30,4);
f = {@(x)0;@(x)x-9;@(x)1;@(x)3.33 - .083*x;@(x)0};
i = discretize(TMP,[-inf,9,10,28,40,inf]);
out = arrayfun(@(x,y)f{y}(x),TMP,i);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by