フィルターのクリア

For Loop Question on index

1 回表示 (過去 30 日間)
Michael Angeles
Michael Angeles 2022 年 1 月 18 日
コメント済み: Michael Angeles 2022 年 1 月 18 日
I have an example data:
Column 1 is Student Number, Column 2-4 are grades
1.0 68.0 45.0 92.0
2.0 83.0 54.0 93.0
3.0 61.0 67.0 91.0
4.0 70.0 66.0 92.0
5.0 75.0 68.0 96.0
6.0 82.0 67.0 90.0
How can I create a for loop that would sum Column 2-4 and relate it back to the student number.
It should print out: "Student" 1 "Total_score" 205 (This added columns 2-4)"
Thanks!
  1 件のコメント
James Tursa
James Tursa 2022 年 1 月 18 日
編集済み: James Tursa 2022 年 1 月 18 日
What have you done so far? What specific problems are you having with your code? Are you required to use a for-loop?

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

採用された回答

Voss
Voss 2022 年 1 月 18 日
data = [ ...
1.0 68.0 45.0 92.0; ...
2.0 83.0 54.0 93.0; ...
3.0 61.0 67.0 91.0; ...
4.0 70.0 66.0 92.0; ...
5.0 75.0 68.0 96.0; ...
6.0 82.0 67.0 90.0; ...
];
total = sum(data(:,2:4),2);
for i = 1:size(data,1)
fprintf('"Student" %d "Total_score" %g (This added columns 2-4)"\n',data(i,1),total(i,1));
end
"Student" 1 "Total_score" 205 (This added columns 2-4)" "Student" 2 "Total_score" 230 (This added columns 2-4)" "Student" 3 "Total_score" 219 (This added columns 2-4)" "Student" 4 "Total_score" 228 (This added columns 2-4)" "Student" 5 "Total_score" 239 (This added columns 2-4)" "Student" 6 "Total_score" 239 (This added columns 2-4)"
Or, if you really want to do the sum in a loop:
total = NaN(size(data,1),1);
for i = 1:size(data,1)
total(i) = data(i,2)+data(i,3)+data(i,4);
end
for i = 1:size(data,1)
fprintf('"Student" %d "Total_score" %g (This added columns 2-4)"\n',data(i,1),total(i,1));
end
"Student" 1 "Total_score" 205 (This added columns 2-4)" "Student" 2 "Total_score" 230 (This added columns 2-4)" "Student" 3 "Total_score" 219 (This added columns 2-4)" "Student" 4 "Total_score" 228 (This added columns 2-4)" "Student" 5 "Total_score" 239 (This added columns 2-4)" "Student" 6 "Total_score" 239 (This added columns 2-4)"
  4 件のコメント
Voss
Voss 2022 年 1 月 18 日
The second 2 is to tell the sum() function to sum along the 2nd dimension. See the description in the documentation here.
Michael Angeles
Michael Angeles 2022 年 1 月 18 日
Thank you!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by