Using nested loop to enter individual values in a matrix

1 view (last 30 days)
Hi, I am trying to use a nested loop to input values of a m x m matrix individually. However after populating the entire matrix it still asks me for one additional value!
How should I solve this problem?
% Inputs
% [A] = M x M matrix
close all, clear all, clc;
% Ask user for size of matrices where [A] = M x M
m = input('What is the value of M, where matrices [A] = m x m? ');
% Create matrices [A]
A = [];
x = 1; y = 1;
while y < m+1;
while x < m+1;
i = input('Matrix A - input value of row x column y: ');
A(y,x) = i;
x = x+1;
end
x = 1;
y = y+1;
j = input('Matrix A - input value of row y column x: ');
A(y, x) = j;
x = x+1;
end
A

Accepted Answer

Voss
Voss on 7 Mar 2023
Basically, you don't need the second input(), after the inner while loop, at all.
close all, clear all, clc;
% Ask user for size of matrices where [A] = M x M
m = input('What is the value of m, where matrix [A] = m x m? ');
% Create matrices [A]
A = zeros(m,m);
y = 1;
while y < m+1
x = 1;
while x < m+1
i = input(sprintf('Matrix A - input value of row %d column %d: ', y, x));
A(y,x) = i;
x = x+1;
end
y = y+1;
end
A

More Answers (0)

Categories

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

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!