フィルターのクリア

How to add final value of a loop part to the next one. i need to add the months answers of ii=1 to ii=12

1 回表示 (過去 30 日間)
clc;
clear;
month =0;
for ii = 1:12
x1 = input('week1:');
x2 = input('week2:');
x3 = input('week3:');
x4 = input('week4:');
month = x1+x2+x3+x4
end
  1 件のコメント
Dennis
Dennis 2018 年 6 月 19 日
Use ii as index:
month(ii)=x1+x2+x3+x4;
Maybe consider indexing x aswell:
for ii=1:2
for k=1:4
x(k)=input(strcat('week',num2str(k)));
end
month(ii)=sum(x);
end
If you want to keep x values you can use x(ii,k) and sum(x(ii,:))

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

回答 (2 件)

Guillaume
Guillaume 2018 年 6 月 19 日
What is the purpose of Xs ?
Do not number variables. If you're numbering variables that is a good indication that you should be using an array instead:
for ii = 1:12
x(1) = ...
x(2) = ...
...
month = sum(x);
end
Even better since you're now using an array, you can use another loop:
for ii = 1:12
for week = 1:4
x(week) = input(sprintf('week%d:', week));
end
month = sum(x);
end
this is much better code. If you need to add another week, you only need to change the endpoint of the loop.
As for your question, if I understood correctly:
month = 0;
for ii = ...
...
month = month + sum(x);
end
  2 件のコメント
Seb Stephen
Seb Stephen 2018 年 6 月 19 日
I wrongly corrected it, don't bother with XS Thanks for correction, i really appreciate it. thanks
Seb Stephen
Seb Stephen 2018 年 6 月 19 日
for the last part , how can i cummulate the months answers? '' month = month + sum(x)''

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


Sayyed Ahmad
Sayyed Ahmad 2018 年 6 月 19 日
編集済み: Sayyed Ahmad 2018 年 6 月 19 日
clc;
clear;
XS =0;
month=0;
for ii = 1:12
x1 = input('week1:');
x2 = input('week2:');
x3 = input('week3:');
x4 = input('week4:');
month = month+x1+x2+x3+x4
end

カテゴリ

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