how to create a matrix (3*3) from 1 to 9 by using for loop

How to create a matrix (3*3) from 1 to 9 by using For loop like:
1 2 3
4 5 6
7 8 9
.................
for i=1:3 %row%
for j=1:3 %column%
a(i,j)= input('a=');
end
end
disp (a)
..................
I wrote this code, but I don't want to input the digits from 1 to 9 by keyboard. I want the computer enter these digits automatically by using For loop

 Accepted Answer

I think you don't need any for loop to achieve this goal. try this code below:
reshape( 1:9, 3, 3) .'

8 Comments

Will note, however, the MATLAB idiom of reshape( 1:9, 3, []) .' to save specifying both shape arguments explicitly--the [] tell ML to compute the necessary size automagically from numel() and the given argument. And, significantly, the order can be either way depending upon which is wanted to be specified in any given case...
Thank u very much, but that's not what i'm looking for. However, thank u very very much to both of u.
dpb
dpb on 22 Dec 2019
Edited: dpb on 22 Dec 2019
Well, what are you looking for, then?
Why in the world would you choose a double loop and indexing over builtin matrix expressions? It's the whole point of there being a MATrixLABoratory product.
It's very difficult to post deliberately obtuse and wrongheaded answers on the Answers forum when there are much better solutions.
It's pretty-much trivial to do but unless can provide more justification for "why", I don't think I'm going to go there. :)
Well, that's what my teacher wants. a matrix (3*3) from 1 to 9 by using for loop. thank you for your patience
dpb
dpb on 22 Dec 2019
Edited: dpb on 22 Dec 2019
Ah! You should have said "homework"!
We don't do homework by giving out solved solutions...we coach/provide hints when student shows their work and where got stuck...so, that said:
OK, you've got two loops each from 1:3. So your problem is how to get 9 integers...
HINT: Think counting...how would you do that you think?
I added the homework tag. Hint based on dpb's coaching:
counter = .....................
for row = 1 : .......................
for col = ....................
output(row, c..............) = ....................
........................
end
end
Surely you can finish it now.
clc,clear
k=1;
for i=1:3
for j = 1:3
a(i,j)=k;
k=k+1;
end
end
disp (a)

Sign in to comment.

More Answers (1)

for i=1:3 for j=1:3 a(i, j) =input('a=') : end end disp(a)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!