Combined value of different arrays with constraints

1 回表示 (過去 30 日間)
Andreas Volden
Andreas Volden 2014 年 12 月 19 日
コメント済み: Andreas Volden 2014 年 12 月 20 日
Hi! I have a problem regarding computing combined values from arrays that not have the same size. For a given timeseries, t, I want my for loop to compute a value if some constraints are fulfilled.
I have a vector p_dh which contains t samples where only t-n are valid and useful. Valid elements of p_dh is given by vector A1.
Another vector A contains values where other constraints are accounted for. To compute the value, given that current element of p_dh is valid(t~= any element of A1), my plan was to use a for loop comprising som if and elseif statements. This pseudo code may be useful for understanding the problem:
for t=1:length(p_dh),
if t == any element of A1,
value(t) = nan;
elseif t == any element of A,
value(t) = p_dh(t) - p_c(t) - constant_a;
else
value(t) = nan;
end
end
In the end I want a vector value of size [1:4020] which has both nan elements and valid numerical values according to the for loop and given constraints. It's worth noticing that lengths of t, A and A1 is individual. t = [1:4020], A = [1:502] and A1 = [1:453]. Can you guys help me out here?
thanks!
  3 件のコメント
Andreas Volden
Andreas Volden 2014 年 12 月 19 日
The code is correct. My text formulation may indicate otherwise, I see that. If the first statement is true(if t == any element of A1), set value to nan and increment t. If this statement is false, move to elseif statement and check t == any element of A. If this is true compute value and then increment t. And so on...
Stephen23
Stephen23 2014 年 12 月 19 日
Do any of the suggested solutions work for you?

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

採用された回答

Thorsten
Thorsten 2014 年 12 月 19 日
result = nan(size(p_th));
for t=1:length(p_th)
if ismember(p_th(t), A)
result(t) = p_th(t) - p_c(t) - constant_a;
end
end
  1 件のコメント
Andreas Volden
Andreas Volden 2014 年 12 月 20 日
Works fine. Thank you!

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

その他の回答 (1 件)

Stephen23
Stephen23 2014 年 12 月 19 日
編集済み: Stephen23 2014 年 12 月 19 日
This is a perfect example of where using vectorization can really help to make MATLAB code neater and faster, by applying some operation to the whole array at once instead of in loops:
First we create some fake data:
p_dh = 0:9;
A = 0:2:8;
A1 = 0:3:9;
then we define the logic of which elements you need:
vec = 1:numel(p_dh);
idx = ismember(vec,A) & ~ismember(vec,A1);
and then simply transfer the data from the original arrays:
out(idx) = p_dh(idx); % + p_c(idx) - constant_a
out(~idx) = nan;
  1 件のコメント
Andreas Volden
Andreas Volden 2014 年 12 月 20 日
This also works fine. Thank you!

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

カテゴリ

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