MATLAB Answers

create a array base on specific condition ?

7 views (last 30 days)
I had a array like this
A=[0 0 0 10 0 0 0 0 8 0 0 5 0 0 0 3 0 2 0 0 0 1 0 0 0];
and now I want to create a array B like this in which
B(4)=10-8=2;
[B(4)=A(4)-next upcoming non zero value ],
B(9)=8-5=3;[B(9)=A(9)-next non zero value]
and similarly for
B(12)=5-3=2;
B(16)=3-2=1;
B(18)=2-1=1;
B(22)=1;
and rest of the B values are zero. thanks
  2 Comments
MUKESH KUMAR
MUKESH KUMAR on 30 Aug 2018
In the B matrix, I just want to put the difference of number at that position to the next non zero number.

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 30 Aug 2018
Edited: Stephen Cobeldick on 30 Aug 2018
>> idx = A~=0;
>> A(idx) = [-diff(A(idx)),1]
A =
0 0 0 2 0 0 0 0 3 0 0 2 0 0 0 1 0 1 0 0 0 1 0 0 0
  5 Comments
MUKESH KUMAR
MUKESH KUMAR on 31 Aug 2018
sorry for that I found correction needed from my side, thanks alot.

Sign in to comment.

More Answers (1)

jonas
jonas on 30 Aug 2018
v=A(find(A~=0));
vid=find(A~=0);
B=A
B(vid)=B(vid)-[v(2:end) 0]
not the most elegant solution

Community Treasure Hunt

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

Start Hunting!