Building a matrix with a for-loop

Hello, I am constructing a matrix using the following program:
%Program HW13.m
x = 35;
y = 26;
n = 5;
for i = 1:1:n+1
x(i+1) = 18*x(i) - 11*y(i);
y(i+1) = 8*x(i) - y(i);
end
The for-loop generates two matrices, one for "x" and one for "y". However, I need to create new matrix: column 1 with the "i" values, column 2 with the iterated "x" values, column 3 with the iterated "y" values, and column 4 with "x/y" values. Any suggestions on how to do this?

回答 (2 件)

Walter Roberson
Walter Roberson 2015 年 10 月 25 日

1 投票

[(1:n+1).', x(:), y(:), x(:)./y(:)]

2 件のコメント

Viktoria Kolpacoff
Viktoria Kolpacoff 2015 年 10 月 25 日
Tried this command; however it says that the dimensions are not consistent.
Star Strider
Star Strider 2015 年 10 月 25 日
That should be:
[(1:n+2).', x(:), y(:), x(:)./y(:)]
because of the way the indices work, so the number of elements is n+1+1.

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

Andrei Bobrov
Andrei Bobrov 2015 年 10 月 25 日

0 投票

n = 5;
out = zeros(n+2,4);
out(1,2) = 35;
out(1,3) = 26;
for ii = 1:n+1
out(ii+1,2) = 18*out(ii,2) - 11*out(ii,3);
out(ii+1,3) = 8*out(ii,2) - out(ii,3);
end
out(:,1) = 1:n+2;
out(:,end) = out(:,2)./out(:,3);

3 件のコメント

Viktoria Kolpacoff
Viktoria Kolpacoff 2015 年 10 月 25 日
編集済み: Viktoria Kolpacoff 2015 年 10 月 25 日
Thank you for your help. However, when I run the program, I get:
out =
1.0e+07 *
0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.0000 0.0000
0.0000 0.0003 0.0002 0.0000
0.0000 0.0034 0.0025 0.0000
0.0000 0.0335 0.0245 0.0000
0.0000 0.3334 0.2434 0.0000
0.0000 3.3235 2.4235 0.0000
Andrei Bobrov
Andrei Bobrov 2015 年 10 月 25 日
>> format short g
>> out
out =
            1           35           26       1.3462
            2          344          254       1.3543
            3         3398         2498       1.3603
            4        33686        24686       1.3646
            5    3.348e+05    2.448e+05       1.3676
            6   3.3336e+06   2.4336e+06       1.3698
            7   3.3235e+07   2.4235e+07       1.3714
Stephen23
Stephen23 2015 年 10 月 25 日
編集済み: Stephen23 2015 年 10 月 25 日
@Viktoria Kolpacoff: what is the problem with that output? Remember that the factor 1.0e+07 * applies to all elements of the displayed array. You can use format to change how output is displayed in the command window.

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

カテゴリ

ヘルプ センター および File ExchangeOperators and Elementary Operations についてさらに検索

質問済み:

2015 年 10 月 25 日

編集済み:

2015 年 10 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by