Using the value of the next step in a FOR loop over a vector

조회 수: 1 (최근 30일)
Christian S.
Christian S. 2020년 10월 5일
댓글: Christian S. 2020년 10월 5일
Hi everybody,
is it possible to use in a for loop over a vector the value of the next step?
e.g. if got a vector like this:
h_x=[0 0 0 -2 -15 -100 -50 50 0 0 0 0]
and a loop using the vector
for test=h_x
if test==0
disp('No')
else
if test-1 ==0
a=test %when the value of the step before was 0, it should just use the value of the current step without any operations into a new Vector 'a'
if test+1 ==0
a=test %when the value of the step after is 0, it should just use the value of the current step without any operations into a new Vector 'a'
end
end
a=h_x+(10*(test+1))+(10*(test-1)) %Here the current value and 10 times the value of the vector step befor and after should be put into the new vector 'a'
end
end
This should result in a vector a like this:
a=[0 0 0 -2 (-15+(10*-2)+(10*-100)) (-100+(10*-15)+(10*-50)) (-50+(10*-100)+(10*50)) 50 0 0 0 0]
a=[0 0 0 -2 -1035 -750 -550 50 0 0 0 0]
Does anyone has a hint for me how to include the next steps of the for loop into the formula?
Thank you in advance and very best
Christian

채택된 답변

Stephen23
Stephen23 2020년 10월 5일
편집: Stephen23 2020년 10월 5일
"Does anyone has a hint for me how to include the next steps of the for loop into the formula?"
In MATLAB it is much better to loop over indices, rather than looping over data values. Then your task is easy:
h_x = [0,0,0,-2,-15,-100,-50,50,0,0,0,0];
a = h_x; % preallocate
for k = 2:numel(h_x)-1 % loop over indices!
v = h_x(k-1:k+1); % sub-vector
if all(v([1,3])) % non-zero
a(k) = v*[10;1;10];
end
end
giving:
>> out
out =
0 0 0 -2 -1035 -750 -550 50 0 0 0
Or you could avoid the loop entirely:
>> x = [0,h_x(1:end-1)];
>> y = [h_x(2:end),0];
>> z = x&y; % non-zero
>> a = [10,1,10]*[x.*z;h_x;y.*z]
a =
0 0 0 -2 -1035 -750 -550 50 0 0 0

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by