Combined value of different arrays with constraints

1 Ansicht (letzte 30 Tage)
Andreas Volden
Andreas Volden am 19 Dez. 2014
Kommentiert: Andreas Volden am 20 Dez. 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 Kommentare
Andreas Volden
Andreas Volden am 19 Dez. 2014
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 am 19 Dez. 2014
Do any of the suggested solutions work for you?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Thorsten
Thorsten am 19 Dez. 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

Weitere Antworten (1)

Stephen23
Stephen23 am 19 Dez. 2014
Bearbeitet: Stephen23 am 19 Dez. 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;

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by