How do I create a square matrix based on user input?
Show older comments
I'm trying to write a program that asks the user what the dimensions of their square matrix are then takes that number, asks for each entry and creates the matrix for the program to use for the rest of the questions. I know how to create one row at a time, but I can't figure out how to put all the rows together to make one matrix.
Answers (5)
Anuj
on 21 Feb 2014
One simple way for this can be, Suppose you have square matrix of order n. So you have n^2 elements. You can enter all the elements one by one and change it into square matrix like this-
n=input('order of your square matrix is? ')
for i=1:n^2;
a(i)=input('elements-');
end
a=reshape(a,n,n)'
Regards
m=input('row')
n=input('column')
for i=1:m
for j=1:n
a(i,j)=input('elements-')
end
end
a=reshape(a,m,n)
4 Comments
Josipa Petricevic
on 5 Dec 2020
Moved: DGM
on 3 Mar 2023
what I have to write in command window instead a(i,j)=input('elements-')?
Walter Roberson
on 5 Dec 2020
Edited: DGM
on 3 Mar 2023
The above code is valid in the command window -- though I would recommend putting in extra spaces,
m=input('row ')
n=input('column ')
for i=1:m
for j=1:n
a(i,j)=input('elements- ')
end
end
a=reshape(a,m,n)
Walter Roberson
on 18 Jan 2021
Edited: DGM
on 3 Mar 2023
unknown nobody
on 15 Aug 2017
a = input('enter the matrix');
[1 2; 3 4]
1 Comment
Peram Balakrishna
on 25 Sep 2021
simple
Gowtham K
on 25 Dec 2021
m=input('row')
n=input('column')
for i=1:m
for j=1:n
a(i,j)=input('elements-')
end
end
a=reshape(a,m,n)
b= a+a
c=a-a
m=a*a
s= a^2
2 Comments
Gowtham K
on 25 Dec 2021
not working for 2*2 matrix but working for 3*3 matrix
The code you posted works for 2x2 just fine. It's entirely unnecessary, tedious and error-prone to force users to enter arrays using input(), but for some reason it's popular to teach people bad ideas like this.
If you have to do things this way, at least make it readable.
% use meaningful prompts with clear formatting and output suppression
m = input('number of rows: ');
n = input('number of columns: ');
a = zeros(m,n); % preallocate
for i=1:m
for j=1:n
a(i,j)=input(sprintf('enter a(%d,%d): ',i,j)); % again
end
end
%a = reshape(a,m,n) % this does nothing. the array is already this shape
b = a+a
c = a-a
m = a*a % this is matrix multiplication, not elementwise multiplication
s = a^2 % same
Categories
Find more on Creating and Concatenating Matrices 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!