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

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 5 Oct 2020
Edited: Stephen23 on 5 Oct 2020
"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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!