I had A vector
A=[1 0 0 2 3 2 3 5 0 0 0 0 1 2 1 0 0 0 0 3 4 0 0 0 0 0 0 1 2 3 2 0 0 0 0 2 0 0]
like this. Now I want a vector B having average of corresponding non-zero value, like
B(1)=average(A(1));
B(4)=average(A(4):A(8));
B(13)=average(A(13):A(15);
B(20)=average(A(20):A(21));
B(28)=average(A(28):A(31)) and so on .....rest values should be zeros.
hence
B=[1 0 0 3 0 0 0 0 0 0 0 0 1.33 0 0 0 0 0 0 3.5 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 2 0 0 ]

5 件のコメント

jonas
jonas 2018 年 9 月 4 日
I've seen a number of your similar questions. Just out of curiosity, can I ask what the application is?
MUKESH KUMAR
MUKESH KUMAR 2018 年 9 月 4 日
I need this for some further more calculation in my problem
jonas
jonas 2018 年 9 月 4 日
Right, I figured that much :)
MUKESH KUMAR
MUKESH KUMAR 2018 年 9 月 4 日
So how can i take average of continuous values at starting point of each continuous group values and rest are zeros.
jonas
jonas 2018 年 9 月 4 日
I'll give it a try in an hour if no one gave you an answer. This one is not as straight-forward as your previous questions, at least to me.

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

 採用された回答

jonas
jonas 2018 年 9 月 4 日
編集済み: jonas 2018 年 9 月 4 日

0 投票

Credits to Guillaume for cleaning up my original code.
A=[1 0 0 2 3 2 3 5 0 0 0 0 1 2 1 0 0 0 0 3 4 0 0 0 0 0 0 1 2 3 2 0 0 0 0 2 0 0];
B=zeros(size(A));
bounds = find(diff([0, A, 0] ~= 0));
starts = bounds(1:2:end);
ends = bounds(2:2:end) - 1;
B(starts) = arrayfun(@(s, e) mean(A(s:e)), starts, ends);

4 件のコメント

MUKESH KUMAR
MUKESH KUMAR 2018 年 9 月 4 日
編集済み: MUKESH KUMAR 2018 年 9 月 4 日
error" Undefined function or variable 'id'." that should be P=id; its working and thanks for help and I also find an alternative of this
C=[1 0 0 5 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 2 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 1 0 0];
for i=1:38
if C(i)==0
AZ(i)=0;
else
BZ(i)=i+C(i)-1;
B(i)= mean(A(1,i:BZ(i)));
end
end
Guillaume
Guillaume 2018 年 9 月 4 日
I would have
P = diff(A ~= 0)
so that it works with negative values as well. This is probably the most efficient solution. nanmean is not needed however. A slightly simpler version:
A = [1 0 0 2 3 2 3 5 0 0 0 0 1 2 1 0 0 0 0 3 4 0 0 0 0 0 0 1 2 3 2 0 0 0 0 2 0 0];
B = zeros(size(A));
bounds = find(diff([0, A, 0] ~= 0));
starts = bounds(1:2:end);
ends = bounds(2:2:end) - 1;
for i = 1:numel(starts)
B(starts(i)) = mean(A(starts(i):ends(i)));
end
The loop can be replaced by the slightly slower but more compact:
B(starts) = arrayfun(@(s, e) mean(A(s:e)), starts, ends);
jonas
jonas 2018 年 9 月 4 日
@Guillaume: Thank you sir, I'll update the code.
@Mukesh: The code should work now. There was a minor error in my original post. You were too quick to grab it :)
MUKESH KUMAR
MUKESH KUMAR 2018 年 9 月 4 日
thanks for your support :)

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by