Combined value of different arrays with constraints
1 view (last 30 days)
Show older comments
Andreas Volden
on 19 Dec 2014
Commented: Andreas Volden
on 20 Dec 2014
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 Comments
Accepted Answer
Thorsten
on 19 Dec 2014
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
More Answers (1)
Stephen23
on 19 Dec 2014
Edited: Stephen23
on 19 Dec 2014
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;
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!