How do i use a pair of nested for loops to store a series of 9 related numbers in a 3x3 matrix?

2 ビュー (過去 30 日間)
the outer loop decides what row and the inner loop decides what column to store each number in the series, the code should prompt the user for the starting number and increment of the series
  5 件のコメント
Sarah Mcmillan
Sarah Mcmillan 2018 年 9 月 6 日
編集済み: James Tursa 2018 年 9 月 6 日
I'm sorry for the confusion, I'm just frustrated. I am trying to do a pair of nested loops so that I can just denote a as the number I want to start with and b the number I want to continuously add. In the end I want my matrix to look like
[1, 2, 3;
4, 5, 6;
7, 8, 9]
for the case that a=1 and b=1, but I want to be able to change a and b to any numbers if I chose to do so.
Right now I have the matrix
[2, 3, 4;
3, 4 , 5;
4, 5 , 6]
as you can see the rows are adding by 1 but the columns are not continuing the counting, they add 1 to the number above it. I need help to figure out so that it continues the counting not whatever its doing now.
David Goodmanson
David Goodmanson 2018 年 9 月 6 日
Does this have to be done with 'for' loops, or is any technique in Matlab all right to use?

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

回答 (2 件)

Dennis
Dennis 2018 年 9 月 6 日
I hope i got the question right (some possible solutions with increasing number of loops):
%no loop
a=1;
b=1;
X=ones(1,9)*a;
Y=ones(1,8)*b;
Y=cumsum(Y);
X(2:end)=X(2:end)+Y;
X=reshape(X,[],3)';
%1 loop
a=1;
b=1;
X=ones(1,9)*a;
for i=1:numel(X)
X(i)=X(i)+(i-1)*b;
end
X=reshape(X,[],3)';
%2 loops
a=1;
b=1;
X=ones(3,3)*a;
for i=1:3
for k=1:3
X(i,k)=a+(i*k-1)*b;
end
end

Stephen23
Stephen23 2018 年 9 月 6 日
編集済み: Stephen23 2018 年 9 月 6 日
"How do i use a pair of nested for loops to store a series of 9 related numbers in a 3x3 matrix?"
num = str2double(input('start number: ','s'));
nrows = 3;
ncols = 3;
mat = nan(nrows,ncols);
for kr = 1:nrows
for kc = 1:ncols
mat(kr,kc) = num;
num = num+1;
end
end
And when run:
start number: 1
>> mat
mat =
1 2 3
4 5 6
7 8 9

カテゴリ

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