Sum with a for loop of each 2 elements

14 ビュー (過去 30 日間)
Ali Tawfik
Ali Tawfik 2020 年 4 月 21 日
コメント済み: Sriram Tadavarty 2020 年 4 月 21 日
Hi All,
I have been trying to get the sum of each two elements: for example:
I have x=[50 200 20], I need to have the output =[250 220]
50+200
then
200+20
and so on...
clear all;
clc;
x=[50 200 20];
%x(1:length(x))=x(length(x):-1:1);
for i=1:length(x)-1
c(i) = sum(x); % c(i)=[250 220]
end

回答 (1 件)

Sriram Tadavarty
Sriram Tadavarty 2020 年 4 月 21 日
編集済み: Sriram Tadavarty 2020 年 4 月 21 日
Hi Ali,
Use the following modification to the code:
clear all;
clc;
x=[50 200 20];
for i=2:length(x)
c(i-1) = x(i-1) + x(i);
end
Use can even use movsum function as shown below:
c = movsum(x,2);
c = c(2:end);
Hope this helps.
Regards,
Sriram
  2 件のコメント
Ali Tawfik
Ali Tawfik 2020 年 4 月 21 日
Hi Sriram,
Thanks for your prompt reply.
actually I do not prefer functions in that situation,
and even when I tried I got the following error
Subscripted assignment dimension mismatch.
So Would you mind helping me to have a command without function ??
thanks,
Sriram Tadavarty
Sriram Tadavarty 2020 年 4 月 21 日
Sure Ali. Can you once look over the modified answer?

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by