Hello all,
Suppose I have a vector and I want to add every five sequential values together. So for example if v1=[1 1 1 1 1 1 1 1 1 1]; Then I'm expecting to get v2 as: v2=[5 5]; How to implement this in matlab?
I tried the following code:
%%%%%%%
v=[1 1 1 1 1 1 1 1 1 1];
for i=1:i+5:length(v)
v2(i)=v(i)+v(i+1)+v(i+2)+v(i+3)+v(i+4)
end
%%%%%%%
But the answer was wrong; it was
v2=[5 0 0 0 0 5]

 採用された回答

per isakson
per isakson 2014 年 3 月 11 日
編集済み: per isakson 2014 年 3 月 11 日

0 投票

A Matlabish way
>> sum( reshape( ones(1,10), 5, [] ) )
ans =
5 5
it assumes that the length of v1 is a multiple of 5

3 件のコメント

Nourhan
Nourhan 2014 年 3 月 11 日
What if the length is not multiples of 5? How can I add zeros?
Sagar Damle
Sagar Damle 2014 年 3 月 11 日
I have used the answer given by per isakson to solve your problem.Try it!
v = [1 1 1 1 1 1 1];
leng = length(v);
x = mod(leng,5);
if x ~= 0
v(leng+1 : leng+(5-x)) = 0;
end
sum( reshape( v, 5, [] ) )
per isakson
per isakson 2014 年 3 月 11 日
編集済み: per isakson 2014 年 3 月 11 日
Yes, pad with zeros is a good idea.
>> v1 = ones( 1, 17 );
>> v1 = cat( 2, v1, zeros( 1, (5-rem(length(v1),5) ) ) );
>> length( v1 )
ans =
20
One-liners is a Matlab sport. However, this one-liner adds an extra five zeros to v1 when length already is a multiple of five (appropriate smiley).
One more try
v1 = cat( 2, v1, zeros( 1, rem((5-rem(length(v1),5)),5) ) );
There is always another edge-case that will error.

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

その他の回答 (0 件)

カテゴリ

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

タグ

質問済み:

2014 年 3 月 11 日

編集済み:

2014 年 3 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by