How do I save results from a loop into a table?

For example, I have a simple code that I want to output the results in the form of a spreadsheet/table. How do I do that?
for a = 1:10
K = a*3
end
Sample output spreadsheet/table that I want:
row ---- column1 : column 2
row 1----- a : k
row 2--- 1 : 3
row 3--- 2 : 6
row 4--- 3 : 9
row n--- .
row n--- .
row n--- .
row 10--- 10 : 30
Your help is greatly appreciated.

回答(1 个)

Often it is much easier and simpler to avoid the loop:
>> A = 1:10;
>> [A.',3*A.']
ans =
1 3
2 6
3 9
4 12
5 15
6 18
7 21
8 24
9 27
10 30
However if you really want to use a loop, then try this:
>> out = A.';
>> for k = 1:numel(A), out(k,2) = 3*A(k); end
>> out
out =
1 3
2 6
3 9
4 12
5 15
6 18
7 21
8 24
9 27
10 30
These kind of basic MATLAB operations are explained in the introductory tutorials, which are recommended for all beginners:

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

提问:

2016-7-6

编辑:

2016-7-6

Community Treasure Hunt

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

Start Hunting!

Translated by