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

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