フィルターのクリア

create a array base on specific condition ?

3 ビュー (過去 30 日間)
MUKESH KUMAR
MUKESH KUMAR 2018 年 8 月 30 日
コメント済み: MUKESH KUMAR 2018 年 8 月 31 日
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 件のコメント
jonas
jonas 2018 年 8 月 30 日
編集済み: jonas 2018 年 8 月 30 日
Question unclear. Please show the complete output of your example. What do you want to do with the last value?
MUKESH KUMAR
MUKESH KUMAR 2018 年 8 月 30 日
In the B matrix, I just want to put the difference of number at that position to the next non zero number.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 8 月 30 日
編集済み: Stephen23 2018 年 8 月 30 日
>> 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 件のコメント
Stephen23
Stephen23 2018 年 8 月 31 日
編集済み: Stephen23 2018 年 8 月 31 日
@MUKESH KUMAR: you get negative values because although in your question you gave values which decrease in magnitude (so their differences are all positive), in your real A data all of the values increase in magnitude (so their differences are all negative). Lets have a look at some of the values:
>> B(find(B))
ans =
-1
-5
-3
-2
... lots more here
-3
-2
1
>> A(find(A))
ans =
1
2
7
10
12
13
... lots more here
128
131
133
In your question you wrote: "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]
Lets try your exact calculation method with the real A values:
B(6334) = A(6334) - A(6478) = -1
B(6478) = A(6478) - A(7487) = -5
B(7487) = A(7487) - A(7543) = -3
...etc
All are negative, all follow the method that you gave in your question, and all are exactly the values that are in B.
MUKESH KUMAR
MUKESH KUMAR 2018 年 8 月 31 日
sorry for that I found correction needed from my side, thanks alot.

サインインしてコメントする。

その他の回答 (1 件)

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by