フィルターのクリア

Using nested loop to enter individual values in a matrix

1 回表示 (過去 30 日間)
Wilbur
Wilbur 2023 年 3 月 7 日
回答済み: Voss 2023 年 3 月 7 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by