best way to update items in arrays value based on -1 and 1
Show older comments
I have the following arrays
The first arr (ArrA), that is the input
The second arr (ArrB) that is the desired results.
Now the logic is that when it see's a 1, the value continues to be a 1, until some new (nonzero) number is found.
When it then sees the new number (eg -1), the following values are then -1, until a new (nonzero) value is found.
So basically it start with 0, 0, 0, it then see's a 1, so the value is 1, until it finds a -1, when it finds that the values are -1 until it finds a 1, and so on.
Numbers int his array will always be either 0, 1, -1.
Now i've been thinking of loops and stuff, but it all seems very complicated with loops within loops
so any help will be appreciated.
ArrA = [0,0,0,1,0,1,0,-1, 0, 0,-1, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0];
ArrB = [0,0,0,1,1,1,1,-1,-1,-1,-1,-1 -1, 1, 1, 1, 1, 1, 1, -1, -1, -1];
Accepted Answer
More Answers (2)
Rik
on 2 Jan 2022
0 votes
Use find to find out how many leading zeros you have. Then set all zeros to 1 and use cumprod. Then set the leading zeros as required.
There is probably a more efficient way to do this, but this will get you most of the way there.
2 Comments
Rizwan Khan
on 2 Jan 2022
That is what the cumprod is for.
% if this is your array:
% [1 0 -1 0]
% then this will be the result of the cumprod call
cumprod([1 1 -1 1])
Although I now realise that this will not work if you have multiple -1 in a stretch:
% [1 0 -1 0 -1]
cumprod([1 1 -1 1 -1])
Walter Roberson
on 2 Jan 2022
0 votes
You do not need loops within loops.
Keep a single variable that records what you are currently converting 0 to.
Scan. At each position, if the input is 1, output is 1, record that you are converting to 1. If the input is -1, output is -1, record that you are converting to -1. Otherwise, input must be 0, and output the recorded value.
WIth some work you can get it down to a single comparison for each input character.
Categories
Find more on Matrix Indexing 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!