Combined value of different arrays with constraints

1 次查看(过去 30 天)
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...

请先登录,再进行评论。

采纳的回答

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 个)

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;

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by