Using nested loop to enter individual values in a matrix

1 次查看(过去 30 天)
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

采纳的回答

Voss
Voss 2023-3-7
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by