I am trying to create a 5x5 array. How will I achieve this by using a nested loop?

78 ビュー (過去 30 日間)
ws
ws 2015 年 11 月 4 日
編集済み: Elisa R 2020 年 9 月 20 日
%%%%%Output should look like this:
A =
1 2 3 4 5 %b
2 4 6 8 10 %c
3 6 9 12 15 %d
4 8 12 16 20 %e
5 10 15 20 25 %f
%%%My code
while (g = b)
for a
(b;c;d;e;f)
fprinf('%d',a)
end
end
  1 件のコメント
dpb
dpb 2015 年 11 月 4 日
while (g = b)
Neither b nor g are defined prior to this statement; nor are any of the others...but even if were the logical operator is == not =

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

回答 (2 件)

Luca Kolibius
Luca Kolibius 2016 年 11 月 12 日
How about
a=(1:25);
reshape(a,[5,5])'
?
  2 件のコメント
Stephen23
Stephen23 2016 年 11 月 12 日
編集済み: Stephen23 2016 年 11 月 12 日
@Luca Kolibius: your code:
>> reshape(1:25,[5,5])'
ans =
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
does not generate what the OP requested:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Elisa R
Elisa R 2020 年 9 月 20 日
編集済み: Elisa R 2020 年 9 月 20 日
Simply removing the ' will, though.
>>a= (1:25)
a = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
>>reshape(1:25,[5,5])
ans =
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25

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


Robert
Robert 2015 年 11 月 4 日
The array you asked for can be created without a nested loop. Try:
(1:5)'*(1:5)
The enclosed statement, (1:5), creates the row vector [1 2 3 4 5]. The single quote in this context transposes the row vector (making it a column vector) and the matrix multiplication of the column and row vectors (in this order) gives you your matrix.
If I read between the lines in your question, I can guess that b, c, d, e, and f are already defined as 1x5 row vectors and you want to make a 5x5 matrix by stacking them on top of each other. In this case, try:
A = [b;c;d;e;f]
In MATLAB, vectors and matrices are enclosed in square brackets. Commas and/or spaces separate columns, and semicolons separate rows. So this code creates a new row for each of the variables b through f. Be careful: this will cause an error if the variables do not all have the same number of columns.
If your particular application requires loops for some reason that isn't apparent in your question, I recommend a for loop over a while loop.

カテゴリ

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