Reputation: 3
I am wondering how to output a for loop in Matlab so that I end up with a table where the first column is the iteration number and the second column is the result of each iteration. I want the results of each iteration to display not just the final answer.
As a very simple example I have the for loop function below.
Thanks.
p=10
for i=[1 2 3 4 5 6 7 8 9]
p=2*p
end
Upvotes: 0
Views: 825
Reputation: 650
In your example, i
is the iteration variable, so you can reference it to get the iteration number.
I'm assuming you meant you want to output an array (not an actual table data structure). To make an array, you can use some simple concatenation:
p = 10;
arr = [];
for i = 1:9 % shortcutting your manual method here
arr = [arr; i p]; % concatenate the current array with the new row
p = p .* 2;
end
Which results in:
arr =
1 10
2 20
3 40
4 80
5 160
6 320
7 640
8 1280
9 2560
If you actually want a table, then you can create the table from the array using the table
function
Upvotes: 0